简体   繁体   English

在List集合中查找对象

[英]Find object inside collection of List

I have five strong-typed List objects. 我有五个强类型的List对象。 Every object inside every List have property Rating and Vote . 每个List每个对象都有属性RatingVote

How can I select only 10 top rated object from all List 's objects? 如何从所有List对象中仅选择10个最高评级对象? if Rating equal then need use Vote 如果Rating等于那么需要使用Vote

Example(select 2 top rated): 示例(选择2最高评分):

List<Film> : List<Film>

0 element: rating = 1, vote = 2;  
1 element: rating = 4, vote = 5;

List<Clubs> : List<Clubs>

0 element: rating  = 5, vote = 3;  
1 element: rating = 4, vote = 3;

Result: 0 element from Clubs and 1 element from Film 结果:来自Clubs 0个元素和来自Film 1个元素

Try something like below 尝试类似下面的内容

var topTen = yourList.OrderBy(x => x.Rating).ThenBy(z => z.Vote).Take(10) 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 其中l1 ... l5是你的清单

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: 如果这些元素类型中没有公共子类 ,则可以使用LINQ使用包含两个属性的通用Tuple<int, int, object> (即rating,vote和原始元素实例)来投影列表。感兴趣。那么你可以做一个简单的查询来选择前10个元素:

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: 您可以使用OrderBy和ThenBy按两个(或更多)字段排序,然后使用Take获取前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 :) 希望有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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