[英]Updating one Generic List<T> with Another Via Linq c#
I'm able to achieve this in a for-each loop.我能够在 for-each 循环中实现这一点。 I'd like to achieve this via linq query to be as concise as possible.
我想通过 linq 查询尽可能简洁地实现这一点。 Here is my foreach sample:
这是我的 foreach 示例:
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)所以本质上,我想返回一个更新的列表(List2)
You are copying the Selected
properties of the items from one list to another.您正在将项目的
Selected
属性从一个列表复制到另一个列表。 I think your foreach loop is too complicated, a cleaner foreach should be like this:我认为你的 foreach 循环太复杂了,一个更干净的 foreach 应该是这样的:
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
.尽管您可以像下面一样使用
List.ForEach
编写单行代码,但我更喜欢使用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.不过,
foreach
循环的性能会更好。 It also prevents null reference exceptions, or ways to deal with them, because it automatically skips items that have no counterpart in list2
.它还可以防止 null 引用异常或处理它们的方法,因为它会自动跳过
list2
中没有对应项的项目。
Note that this works because list1
is an in-memory list, which I infer from your example.请注意,这是有效的,因为
list1
是一个内存列表,我从您的示例中推断出来。 If list1
is an IEnumerable
it will be repopulated when it's accessed later on in the code, erasing the previous changes.如果
list1
是一个IEnumerable
,它将在稍后在代码中访问时重新填充,从而删除以前的更改。
You can do this with a combination of Where()
and ForEach()
method.您可以结合使用
Where()
和ForEach()
方法来做到这一点。
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()
:如果您不想使用
ForEach()
,可以将其与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更新:感谢@canton7,我解决了问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.