I have two lists
List<objA> List1 List<objA> List2
I want to compare these two list on ID
field, once a match is found I want to compare another field Distace
amongst these two lists and grab the object with the lower value.
Using Linq isn't is not giving the result I want, atleast for the first part of the problem.
var test = List1.Select(x => x.ID) .Intersect(List2.Select(y => y.ID));
Here's one way you could do this with Linq. Firstly, join the two lists together with Union
. Then, group them by the Id
field. Lastly, order those sub lists by Distance
within the grouping, and take the first one of each to get a list of objects by Id
with the minimum available distance.
var aList = new[]
{
new SomeObject() { Id = 1, Distance = 3 },
new SomeObject() { Id = 2, Distance = 5 }
};
var bList = new[]
{
new SomeObject() { Id = 1, Distance = 2 },
new SomeObject() { Id = 2, Distance = 6 }
};
var results = aList
.Union(bList)
.GroupBy(a => a.Id, a => a)
.Select(a => a.OrderBy(b => b.Distance).First());
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.