I have two lists lets say:
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"}]
What is the best way to update elements in List2
with values from elements in List1
based on the condition that the value of name in List1
is equal to value of name in List2
I'm hoping I can find a solution using LINQ, like one below used to select elements
var list = List2.FindAll(y => List1.Any(x => y.name==x.name));
Since your condition is a simple "equals" condition, you can use a join
from source in list1
join target in list2 on source.name equals target.name
select new {target.name, source.limit}
Here's a simple test based on the data from the question:
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}");
}
Outputs:
name = john, limit = 21
name = john, limit = 21
name = edith, limit = 21
name = sam, limit = 50
name = sam, limit = 50
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.