Linq Question

  • Thread starter Thread starter rd
  • Start date Start date
R

rd

Hi,

Suppose I have the below collection of account object and I want to select a
single account with the largest savings. Putting aside the fact that the
below would cause an exception if there were more than one account with
Savings = 40, is this a good way to search the collection? Is there a better
way?

var accounts = new []
{
new {Savings = 20, Owner = "Mary"},
new {Savings = 30, Owner = "Jack"},
new {Savings = 40, Owner = "Bill"}
};

var account = accounts.Single(y => y.Savings == (accounts.Max(x =>
x.Savings)));

Console.Write(account.Owner); // Bill

Regards,
Rich
 
rd said:
Hi,

Suppose I have the below collection of account object and I want to select a
single account with the largest savings. Putting aside the fact that the
below would cause an exception if there were more than one account with
Savings = 40, is this a good way to search the collection? Is there a better
way?

var accounts = new []
{
new {Savings = 20, Owner = "Mary"},
new {Savings = 30, Owner = "Jack"},
new {Savings = 40, Owner = "Bill"}
};

var account = accounts.Single(y => y.Savings == (accounts.Max(x =>
x.Savings)));

Console.Write(account.Owner); // Bill

Regards,
Rich

That will loop the collection twice. Something like this would be better:

int highest = int.MinValue;
var account = accounts.LastOrDefault(x => if (x.Savings > highest) {
highest = x.Savings; return true; } else { return false; } );
 
rd said:
var account = accounts.Single(y => y.Savings == (accounts.Max(x =>
x.Savings)));

Actually, come to think of it, without an SQL engine to optimise the
inner query to run only once, you will be looping the collection one
extra time for each item. If you have 1000 items in the collection, you
will be looping it 1001 times... That's really bad...
 
var superSaverAccount=(from account in accounts
orderby account.Savings
select account).Last();
 
DabblerNL said:
var superSaverAccount=(from account in accounts
orderby account.Savings
select account).Last();

That's better than the oiginal, but still not as efficient as only
looping through the items once and keep track of the highest value.
 
Back
Top