如何让 LINQ 返回具有给定属性最大值的对象? [重复]

问题描述 投票:0回答:10

如果我有一个类似这样的课程:

public class Item
{
    public int ClientID { get; set; }
    public int ID { get; set; }
}

以及这些物品的集合...

List<Item> items = getItems();

如何使用 LINQ 返回具有最高 ID 的单个“Item”对象?

如果我做类似的事情:

items.Select(i => i.ID).Max(); 

我只会得到最高的ID,而我真正想要返回的是具有最高ID的Item对象本身?我希望它返回一个“Item”对象,而不是一个 int。

c# linq linq-to-objects
10个回答
216
投票

这只会循环一次。

Item biggest = items.Aggregate((i1,i2) => i1.ID > i2.ID ? i1 : i2);

谢谢尼克 - 这是证据

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<Item> items1 = new List<Item>()
        {
            new Item(){ ClientID = 1, ID = 1},
            new Item(){ ClientID = 2, ID = 2},
            new Item(){ ClientID = 3, ID = 3},
            new Item(){ ClientID = 4, ID = 4},
        };
        Item biggest1 = items1.Aggregate((i1, i2) => i1.ID > i2.ID ? i1 : i2);

        Console.WriteLine(biggest1.ID);
        Console.ReadKey();
    }


}

public class Item
{
    public int ClientID { get; set; }
    public int ID { get; set; }
}  

重新排列列表并得到相同的结果


117
投票
.OrderByDescending(i=>i.id).First()

考虑到性能问题,这种方法理论上很可能比线性方法慢。然而,实际上,大多数时候我们处理的数据集并不大到足以产生任何影响。

如果性能是主要考虑因素,Seattle Leonard 的答案应该为您提供线性时间复杂度。或者,您也可以考虑从不同的数据结构开始,该数据结构在恒定时间返回最大值项。

First()
将执行与
Take(1)
相同的操作,但直接返回项目而不是包含该项目的枚举。


41
投票
int max = items.Max(i => i.ID);
var item = items.First(x => x.ID == max);

这当然假设 items 集合中有元素。


39
投票

使用

MaxBy

items.MaxBy(i => i.ID);

(之前来自 morelinq 项目,但自版本 6 起它已成为 .NET 的一部分)


10
投票

这是源自@Seattle Leonard 的答案的扩展方法:

 public static T GetMax<T,U>(this IEnumerable<T> data, Func<T,U> f) where U:IComparable
 {
     return data.Aggregate((i1, i2) => f(i1).CompareTo(f(i2))>0 ? i1 : i2);
 }

6
投票

如果你不想使用MoreLINQ并且想要获得线性时间,你也可以使用

Aggregate
:

var maxItem = 
  items.Aggregate(
    new { Max = Int32.MinValue, Item = (Item)null },
    (state, el) => (el.ID > state.Max) 
      ? new { Max = el.ID, Item = el } : state).Item;

这会记住匿名类型中的当前最大元素 (

Item
) 和当前最大值 (
Item
)。然后你只需选择
Item
属性。这确实有点难看,你可以将它包装到
MaxBy
扩展方法中以获得与 MoreLINQ 相同的东西:

public static T MaxBy(this IEnumerable<T> items, Func<T, int> f) {
  return items.Aggregate(
    new { Max = Int32.MinValue, Item = default(T) },
    (state, el) => {
      var current = f(el.ID);
      if (current > state.Max) 
        return new { Max = current, Item = el };
      else 
        return state; 
    }).Item;
}

5
投票

或者你可以编写自己的扩展方法:

static partial class Extensions
{
    public static T WhereMax<T, U>(this IEnumerable<T> items, Func<T, U> selector)
    {
        if (!items.Any())
        {
            throw new InvalidOperationException("Empty input sequence");
        }

        var comparer = Comparer<U>.Default;
        T   maxItem  = items.First();
        U   maxValue = selector(maxItem);

        foreach (T item in items.Skip(1))
        {
            // Get the value of the item and compare it to the current max.
            U value = selector(item);
            if (comparer.Compare(value, maxValue) > 0)
            {
                maxValue = value;
                maxItem  = item;
            }
        }

        return maxItem;
    }
}

3
投票

试试这个:

var maxid = from i in items
            group i by i.clientid int g
            select new { id = g.Max(i=>i.ID }

3
投票

在LINQ中你可以通过以下方式解决:

Item itemMax = (from i in items
     let maxId = items.Max(m => m.ID)
     where i.ID == maxId
     select i).FirstOrDefault();

1
投票

您可以使用捕获的变量。

Item result = items.FirstOrDefault();
items.ForEach(x =>
{
  if(result.ID < x.ID)
    result = x;
});
© www.soinside.com 2019 - 2024. All rights reserved.