3

I have this list of id's:

string[] ids = { "AF1", "AF2", "AF3" };

and my goal is to intersect the ids of this list with the table below and sum the age in a single linq query without making a foreach:

   PersonId  |Name        |Age
    AF1      |John        |20
    AF2      |Oscar       |50        
    AF3      |Peter       |30        
    AF4      |Abbey       |65        
    AF5      |Adrian      |43        
    AF6      |Barbara     |15 

i found that by doing:

order.Lines.Select(x => x.PersonId).Intersect(ids);

i get all the id's in the table but didnt found a way to sum the age :/ the output must be 100

Luís Tiago
  • 113
  • 2
  • 10

3 Answers3

2

By using .Select() you are throwing away all info except the IDs, so the Age becomes unreachable. A better approach is by using .Where() and .Contains(), and then you can sum the Age fields that are returned from that:

var sumOfAges = order.Lines.Where(x => ids.Contains(x.PersonId)).Sum(x => x.Age);
Peter B
  • 22,460
  • 5
  • 32
  • 69
1

A solution can be likes the following:

var sum = order.Lines.Where(x => ids.Any(x.PersonId)).Sum(x=> x.Age);
OmG
  • 18,337
  • 10
  • 57
  • 90
0

Not exactly what you wanted but if anyone else comes across this

Sum per id:

var ids = new string[] {"AF1", "AF2", "AF3"};
var persons = new Person[]
{
    new Person("AF1", "John", 20),
    new Person("AF1", "Oscar", 50),
    new Person("AF2", "Peter", 30),
    new Person("AF2", "Abbey", 65),
    new Person("AF3", "Adrian", 43),
    new Person("AF3", "Barbara", 15)
};
var groups = persons.Where(p => ids.Contains(p.PersonId)).GroupBy(p => p.PersonId);
foreach (var group in groups)
{
    Console.WriteLine(group.Key + ": " + group.Sum(p => p.Age));
}
Ferhat Sayan
  • 216
  • 1
  • 4
  • 19