Reputation: 9278
I have five strong-typed List
objects. Every object inside every List
have property Rating
and Vote
.
How can I select only 10 top rated object from all List
's objects? if Rating
equal then need use Vote
Example(select 2 top rated):
List<Film>
:
0 element: rating = 1, vote = 2; 1 element: rating = 4, vote = 5;
List<Clubs>
:
0 element: rating = 5, vote = 3; 1 element: rating = 4, vote = 3;
Result: 0 element from Clubs
and 1 element from Film
Upvotes: 3
Views: 402
Reputation: 24167
If there is no common sub-class among these element types, you can use LINQ to project the lists using a generic Tuple<int, int, object>
(i.e. rating, vote, and the original element instance) containing the two properties you are interested in. Then you can do a simple query to pick the top 10 elements:
List<A> ax = /* ... */;
List<B> bx = /* ... */;
List<C> cx = /* ... */;
/* ... */
IEnumerable<Tuple<int, int, object>> ratingsAndVotes =
ax.Select((a) => Tuple.Create(a.Rating, a.Vote, a)).Concat(
bx.Select((b) => Tuple.Create(b.Rating, b.Vote, b)).Concat(
cx.Select((c) => Tuple.Create(c.Rating, c.Vote, c)) /* ... */;
Tuple<int, int, object>[] topTenItems =
ratingsAndVotes.OrderByDescending((i) => i.Item1).ThenByDescending((i) => i.Item2).Take(10).ToArray();
// topTenItems now contains the top 10 items out of all the lists;
// for each tuple element, Item1 = rating, Item2 = vote,
// Item3 = original list item (as object)
Upvotes: 2
Reputation:
You can use OrderBy and ThenBy to order by two (or more) fields and then use Take to get the top 10:
var myList = new List<Film>();
// ... populate list with some stuff
var top10 = myList.OrderBy(f => f.Rating).ThenBy(f => f.Vote).Take(10);
Hope that helps :)
Upvotes: 1
Reputation: 33242
You can start with something like:
var res = l1.Concat(l2).Concat(l3).Concat(l4).Concat(l5)
.OrderByDescending(k => k.Rating)
.ThenBy(k=>k.Vote)
.Take(10).ToList();
where l1...l5 are your lists
Upvotes: 3
Reputation: 1317
Try something like below
var topTen = yourList.OrderBy(x => x.Rating).ThenBy(z => z.Vote).Take(10)
Upvotes: 8