Linq to update a collection with values from another collection?

前端 未结 5 1188
北恋
北恋 2020-12-31 04:05

I have IQueryable baseList

and List someData

What I want to do is update attributes in some

5条回答
  •  悲&欢浪女
    2020-12-31 04:28

    You can't simply find objects that are in one list but not the other, because they are two different types. I'll assume you're comparing a property called OtherProperty that is common to the two different classes, and shares the same type. In that case, using nothing but Linq queries:

    // update those items that match by creating a new item with an
    // updated property
    var updated =
        from d in data
        join b in baseList on d.OtherProperty equals b.OtherProperty
        select new MyType()
        {
            PropertyToUpdate = d.PropertyToUpdate,
            OtherProperty = d.OtherProperty
        };
    
    // and now add to that all the items in baseList that weren't found in data
    var result =
        (from b in baseList
         where !updated.Select(x => x.OtherProperty).Contains(b.OtherProperty)
         select b).Concat(updated);
    

提交回复
热议问题