【发布时间】:2019-01-14 19:08:26
【问题描述】:
我不只是想在列表中找到最大值。我试图找到给定字符串标题具有最大值的每个对象。最终结果将是一个列表对象,其中只有具有最大值的对象。
我似乎无法让我的 LINQ 语句工作。它一直拉取最大整数值,而不是拉取具有最大整数值的对象。
另外,如果有更有效的路线而不是循环遍历列表 - 我完全赞成。
非常感谢任何帮助
编辑这不是this link suggested by 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;
}
【问题讨论】:
-
查看分组依据,然后从每个组中选择最大值:stackoverflow.com/questions/43804896/…