简体   繁体   中英

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:

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

apologies to those that made the comments. PhraseNum is always an int number but in a string field. It was set to string because of the way it's read from Excel

Linq has a Max extension method. Try like:

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

You can use .Max() from Linq. Here you don't need 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

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.

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 :

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

Or without the TryParse :

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

This Code Return 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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