简体   繁体   中英

Updating one Generic List<T> with Another Via Linq c#

I'm able to achieve this in a for-each loop. I'd like to achieve this via linq query to be as concise as possible. Here is my foreach sample:

 foreach (var item in List2)
 {
     List1.Where(m => m.id == item.id).FirstOrDefault().Selected = item.Selected;
 }

So essentially, I'd like to return an updated list (List2)

You are copying the Selected properties of the items from one list to another. I think your foreach loop is too complicated, a cleaner foreach should be like this:

foreach (var item in List1)
{
    item.Selected = List2.First(m => m.id == item.id).Selected;
}

Although you may write one-liner using List.ForEach like below, but I prefer using foreach .

List1.ForEach(item => item.Selected = List2.First(m => m.id == item.id).Selected);

I prefer to do things like that by joining the lists.

var joined = from i1 in list1
             join i2 in list2 on i1.id = i2.id
             select new { i1, i2 };
joined.ToList().Foreach(x => x.i1.Selected = x.i2.Selected);

This is probably the most succinct way to do it. A foreach loop will perform better though. It also prevents null reference exceptions, or ways to deal with them, because it automatically skips items that have no counterpart in list2 .

Note that this works because list1 is an in-memory list, which I infer from your example. If list1 is an IEnumerable it will be repopulated when it's accessed later on in the code, erasing the previous changes.

You can do this with a combination of Where() and ForEach() method.

List1.Where(x => List2.Where(y=> y.id == x.id).ToList().Count > 0).ToList().ForEach(x => x.Selected = List2.FirstOrDefault(y => x.id == y.id).Selected)

and if you don't want to use ForEach() , you can use this with Select() :

List1 = List1.Where(x => List2.Where(y=> y.id == x.id).ToList().Count > 0).ToList().Select(x => {x.Value = List2.FirstOrDefault(y => x.id == y.id).Value; return x;}).Concat(List1.Where(x => List2.Where(y=> y.id == x.id).ToList().Count == 0)).ToList();

However, it's too long in my opinion

Update: I fixed the problems Thanks to @canton7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM