C# 使用 LINQ 过滤对象列表中具有最大值的每个对象

bag*_*ilk 2 c# linq list max

我不只是想在列表中找到最大值。我正在尝试为给定的字符串标题找到具有最大值的每个对象。最终结果将是一个列表对象,其中只有具有最大值的对象。

我似乎无法让我的 LINQ 语句起作用。它不断拉取最大整数值,而不是拉取具有最大整数值的对象。

另外,如果有更有效的路线而不是循环遍历列表 - 我完全赞成。

任何帮助是极大的赞赏

编辑这不是Servy建议此链接的重复
如果@Servy 专注于阅读文本而不是比较标题,他/她会发现这是完全不同的,那么这不是 Servy。该链接想要找到对象的单个最大值。这不是我要问的。

这是我当前的代码:

public class Prop {     
    public string title {get;set;}
    public int val {get;set;}       
}   

public static void Main()
{
    List<Prop> list = new List<Prop>();
    list.Add(newProp("voltage", 7));
    list.Add(newProp("voltage", 24));
    list.Add(newProp("systemconfiguration", 2451));
    list.Add(newProp("systemunit", 0));
    list.Add(newProp("systemunit", 15));
    list.Add(newProp("voltage", 0));


    List<Prop> newList = new List<Prop>();

    foreach (var p in list) {
        var newP = list.Select(r => r).Where(t => t.title == p.title).Max(v => v.val);  
        Console.WriteLine(newP.ToString());  
        //This is returning the maximum integer found per title

       //newList.Add(newP);    <---- I cannot do this because newP is an Int
    }

    /*
       I need the output of this example to only contain:

           voltage, 24
           systemconfiguration, 2451
           systemunit 15

      As these are the maximum values per title in the list of objects.

    */

}

public static Prop newProp(string t, int v) {
    Prop item = new Prop();
    item.title = t;
    item.val = v;
    return item;    
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

您可以通过GroupBy每个组中的简单和后续排序立即获得所需的结果:

var highestByTitle = list
    .GroupBy(t => t.title)
    .Select(g => g.OrderByDescending(t => t.val).First())
    .ToList();
Run Code Online (Sandbox Code Playgroud)

演示。