简体   繁体   English

如何使用 LINQ 在列表中找到最大值?

[英]How can I find the maximum value in a List using LINQ?

I have this list:我有这个清单:

public static List<PhraseModel> phraseList;

Where the PhraseModel class looks like this: PhraseModel class 如下所示:

public class PhraseModel
{
    public string PhraseId { get; set; }
    public string English { get; set; }
    public string PhraseNum { get; set; }

}

How can I find the maximum value of PhraseNum using LINQ如何使用 LINQ 找到 PhraseNum 的最大值

apologies to those that made the comments.向发表评论的人道歉。 PhraseNum is always an int number but in a string field. PhraseNum 始终是 int 数字,但在字符串字段中。 It was set to string because of the way it's read from Excel由于从 Excel 读取的方式,它被设置为字符串

Linq has a Max extension method. Linq 有一个 Max 扩展方法。 Try like:试试看:

phraseList.Max(x=>int.Parse(x.PhraseNum));

You can use .Max() from Linq.您可以使用.Max() Here you don't need Select()在这里你不需要Select()

int result = phraseList.Max(x => int.Parse(x.PhraseNum));
Console.WriteLine(result); //max PhraseNum from list

To avoid exception you can use int.TryParse() mentioned by @haldo为避免异常,您可以使用@haldo 提到的int.TryParse()

Like,喜欢,

//This is C# 7 Out variable feature. 
int result = phraseList.Max(p => int.TryParse(p.PhraseNum, out int phraseNumInt) ? phraseNumInt: int.MinValue);

You can use TryParse instead of Parse to avoid exception if there's a chance PhraseNum is not an int.如果PhraseNum有可能不是 int,您可以使用TryParse而不是Parse来避免异常。

int tmp;
var max = phraseList.Max(p => int.TryParse(p.PhraseNum, out tmp) ? tmp : int.MinValue);

If you're using C# 7.0 or above you can use the following syntax with inline variable declaration inside the TryParse :如果您使用 C# 7.0 或更高版本,您可以在TryParse中使用以下语法和内联变量声明:

var max = phraseList.Max(p => int.TryParse(p.PhraseNum, out int tmp) ? tmp : int.MinValue);

Or without the TryParse :或者没有TryParse

var max = phraseList.Max(p => int.Parse(p.PhraseNum));

This Code Return 8此代码返回 8

PhraseModel phraseModel = new PhraseModel() { PhraseNum = "5" };
phraseList.Add(phraseModel);
PhraseModel phraseModel2 = new PhraseModel() { PhraseNum = "3" };
phraseList.Add(phraseModel2);
PhraseModel phraseModel3 = new PhraseModel() { PhraseNum = "4" };
phraseList.Add(phraseModel3);
PhraseModel phraseModel4 = new PhraseModel() { PhraseNum = "8" };
phraseList.Add(phraseModel4);

int number;

var maxPhraseNumber = phraseList.Select(n => int.TryParse(n.PhraseNum, out number) ? number : 0).Max();

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

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