开发者

How do I Pick the best performer from a set using LINQ

Given 开发者_开发百科a set var battingContribution = IQueryable<Player, Runs> (Basically a list of players and their total batting score) and another set var bowlingContribution = IQueryable<Player, Runs>, how do I pick whose net contribution was the best such that the player whose batting score minus the bowling score results in the highest net total?


Assuming that you have IDictionary<Player, Runs> instead of IQueryable (which doesn't have two type parameters):

// 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;

You can chain these together for terseness if you prefer.


The following works only for Players that are in both Contributions (although I don't know an IQueryable with two type params):

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 reference to Linq samples see http://msdn.microsoft.com/en-us/vcsharp/aa336746

EDIT - as per comment from OP for completeness:

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜