在List集合中查找对象

本文关键字:查找 对象 集合 List | 更新日期: 2023-09-27 18:18:36

我有五个强类型的List对象。每个List中的每个对象都有属性RatingVote

我如何从所有List的对象中只选择10个评级最高的对象?如果Rating相等,则需要使用Vote

示例(select 2 top rated):

List<Film>:

<>之前0元素:评分= 1,投票= 2;1元素:评分= 4,投票= 5;之前

List<Clubs>:

<>之前0元素:评分= 5,投票= 3;1元素:评分= 4,投票= 3;之前

Result: 0 element from Clubs and 1 element from Film

在List集合中查找对象

试试下面的内容

var topTen = yourList。order (x => x. rating)。then (z => z. vote).Take(10)

你可以这样开始:

  var res = l1.Concat(l2).Concat(l3).Concat(l4).Concat(l5)
                    .OrderByDescending(k => k.Rating)
                    .ThenBy(k=>k.Vote)
                    .Take(10).ToList();

, l1……

如果在这些元素类型中没有共同的子类,您可以使用LINQ使用包含您感兴趣的两个属性的通用Tuple<int, int, object>(即评级,投票和原始元素实例)来投影列表。然后,您可以执行一个简单的查询来选择前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)

您可以使用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);

希望有帮助