如何使用LINQ从集合中选择最佳表现者

时间:2011-09-14 09:16:32

标签: c# linq

给定一组var battingContribution = IQueryable<Player, Runs>(基本上是一个球员名单及其总击球得分)和另一组var bowlingContribution = IQueryable<Player, Runs>,我如何选择其净贡献最佳,以使得击球得分减去的球员保龄球得分导致最高净总数?

2 个答案:

答案 0 :(得分:2)

假设您有IDictionary<Player, Runs>而不是IQueryable(没有两个类型参数):

// Just to make sure that we don't get exceptions if a player is only in one
// of the two collections -- you might want to handle this case differently
var players = battingContribution.Keys.Intersect(bowlingContribution.Keys);

// Put each player and their performance into what is essentialy a tuple
var performance = players.Select(p => 
    new {
        Player = p,
        Performance = battingContribution[p] - bowlingContribution[p]
    });

// Sorting
var orderedPerformance = performance.OrderByDescending(item => item.Performance);

// Selecting best performer
var bestPerformer = orderedPerformance.First().Player;

如果您愿意,可以将这些链接在一起以表示简洁。

答案 1 :(得分:1)

以下内容仅适用于两个贡献中的Players(虽然我不知道有两种类型参数的IQueryable):

var BestPlayer = (from a in (from bt in battingContribution from bw in BowlingContribution where bt.Player == bw.Player select new { Player = bt.Player, Diff = bt.Runs - bw.Runs)) orderby a.Diff descending select a).First().Player;

MSDN对Linq样本的引用,请参阅http://msdn.microsoft.com/en-us/vcsharp/aa336746

编辑 - 根据OP的评论完整性:

var BestPlayer = (from a in (from bt in batRuns from bw in bowlRuns where bt.Player == bw.Player select new { Player = bt.Player, Diff = bt.Runs - bw.Runs}) orderby a.Diff descending select a).First();