我有这个清单:
public static List<PhraseModel> phraseList;
Run Code Online (Sandbox Code Playgroud)
PhraseModel类如下所示:
public class PhraseModel
{
public string PhraseId { get; set; }
public string English { get; set; }
public string PhraseNum { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如何使用LINQ查找PhraseNum的最大值
对发表评论的人表示歉意。PhraseNum始终是一个整数,但在字符串字段中。由于它是从Excel读取的方式,因此将其设置为字符串
Linq具有Max扩展方法。试试:
phraseList.Max(x=>int.Parse(x.PhraseNum));
Run Code Online (Sandbox Code Playgroud)
您可以.Max()从Linq 使用 。在这里你不需要Select()
int result = phraseList.Max(x => int.Parse(x.PhraseNum));
Console.WriteLine(result); //max PhraseNum from list
Run Code Online (Sandbox Code Playgroud)
为了避免异常,您可以使用int.TryParse()@haldo提及的内容
喜欢,
//This is C# 7 Out variable feature.
int result = phraseList.Max(p => int.TryParse(p.PhraseNum, out int phraseNumInt) ? phraseNumInt: int.MinValue);
Run Code Online (Sandbox Code Playgroud)