我有两个列表可以说:
List1 = [{"name":"john", "limit":"21"},{"name":"edith", "limit":"21"}, {"name":"sam", "limit":"50"}]
List2 = [{"name":"john", "limit":"21"},{"name":"john", "limit":"21"} {"name":"edith", "limit":"21"}, {"name":"sam", "limit":"30"}, {"name":"sam", "limit":"30"}]
根据List2
中name的值等于{{name}中的name的条件),用List1
中元素的值更新List1
中元素的最佳方法是什么{1}}
我希望可以使用LINQ找到解决方案,就像下面用来选择元素的解决方案
List2
答案 0 :(得分:0)
由于您的条件是简单的“等于”条件,因此可以使用联接
from source in list1
join target in list2 on source.name equals target.name
select new {target.name, source.limit}
这是一个基于问题数据的简单测试:
var list1 = new List<dynamic>{new {name = "john", limit = "21"}, new {name = "edith", limit = "21"}, new {name = "sam", limit = "50"}};
var list2 = new List<dynamic>{new {name = "john", limit = "21"}, new {name = "john", limit = "21"}, new {name = "edith", limit = "21"}, new {name = "sam", limit = "30"}, new {name = "sam", limit = "30"}};
var query = from source in list1
join target in list2 on source.name equals target.name
select new {target.name, source.limit};
foreach (var x in query)
{
Console.WriteLine($"name = {x.name}, limit = {x.limit}");
}
输出:
name = john, limit = 21
name = john, limit = 21
name = edith, limit = 21
name = sam, limit = 50
name = sam, limit = 50