猿问

列表内的列表中的LINQ Max()

我正在为LINQ查询而苦苦挣扎。我必须在所有选区(使用选区列表)中找到候选人的最高投票价值(最高),并获取ConstituencyName,CandidateName和Votes值。这意味着我必须在两个列表中找到最大值,然后选择对象选区(或至少获取其值)。


public class ListOfConstituencies()

{

    public List<Constituency> Constituencies {get;set;}

}


public class Constituency

{

    public string ConstituencyName {get;set;}

    public List<Candidate> Candidates {get;set;}

}


public class Candidate

{

    public string CandidateName {get;set;}

    public int Votes {get;set;}

}


胡说叔叔
浏览 129回答 3
3回答

慕桂英3389331

您可以将匿名与orderbydescending结合使用来解决此问题。var contituencyWithMostVotes = Constituencies&nbsp; &nbsp; .Select(c => new&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Contituency = c,&nbsp; &nbsp; &nbsp; &nbsp; Candidate = c.Candidates.OrderByDescending(can => can.Votes).First()&nbsp; &nbsp; })&nbsp; &nbsp; .OrderByDescending(c => c.Candidate.Votes).First();结果“contituencyWithMostVotes”是一个具有 2 个属性的匿名对象。实际选区对象该选区中票数最高的候选人。您可以从这些属性中检索所有信息。
随时随地看视频慕课网APP
我要回答