简体   繁体   中英

Find object inside collection of List

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

Try something like below

var topTen = yourList.OrderBy(x => x.Rating).ThenBy(z => z.Vote).Take(10)

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

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> (ie 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)

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 :)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM