C# Group by or something else?
I have a List of type RGBComparison which I created. It has euclidean distance, id, local id, etc as variables. After I sort the List by distances I have an output like this;
1.35363 id=3 1.43554 id=2 1.4556 id=3 1.5 id = 35 1.6 id = 2
======================================
etc. They are sub images' euclidean distances(variable name distance) from the input subimage. I want to group them by keeping the original order. Consider there are 8 distances from image id 1 (and image id 1 is the closest one, 1st one in the list). I want an output like
1.35363 id=3 1.4556 id=3 1.43554 id=2 1.6 id=2 1.5 id = 35 ....
Is there a way to do this? Also I will only take max 5 distances from an input. For example, if id 1 has 8 submage distances in the List, then I will only take the first 5. Later I will 开发者_开发知识库show these subimages on the original image.
I would really appreciate any help.
If your have your data in a list distances
you can use a combination of OrderBy
/GroupBy
, Take
and finally SelectMany
to flatten the result list:
var results = distances.OrderBy( x=> x.Id)
.GroupBy(x => x.Id)
.Select(g => g.OrderBy(x => x.Distance).Take(5))
.SelectMany(x => x)
.ToList() ;
To limit the number of distances to 5 max for each Id you do need the grouping, also use of an OrderBy
before the grouping to induce the correct order of Ids which is preserved by the grouping.
Edit in response to comment and clarification:
var results = distances.GroupBy(x => x.Id)
.Select(g => g.OrderBy(x => x.Distance).Take(5))
.SelectMany(x => x)
.OrderBy( x=> x.Distance)
.ToList();
This should give you a list sorted by distance, with at most 5 elements for any id.
you can use LINQ to sort your list pretty easily
var myRGBComparisonList = new List<RGBComparison>();
//... populate list somewhere
var sortedSequence = from rgbComparison in myRGBComparisonList
orderby rgbComparison.ID ascending, rgbComparison.Distance ascending
select rgbComparison;
精彩评论