I am wondering which one I should choose between the following two options when I need to calculate the sum of Data
of the student with Id
of 1.
var out1 = students
.Select(x => new { Id = x.Id, Sum = x.Data.SelectMany(n => n).Sum() })
.FirstOrDefault(s => s.Id == 1)
.Sum;
var out2 = students
.FirstOrDefault(s => s.Id == 1)
.Data.SelectMany(n => n)
.Sum();
Any comments are welcome.
class Student
{
public int Id { get; set; }
public List<List<int>> Data { get; set; }
}
class Program
{
static void Main()
{
var a = new Student
{
Id = 1,
Data = new List<List<int>>
{
new List<int>{ 1,2,3},
new List<int>{ 4,5,6}
}
};
var b = new Student
{
Id = 2,
Data = new List<List<int>>
{
new List<int>{ 7,8,9},
new List<int>{ 10,11,12}
}
};
var c = new Student
{
Id = 3,
Data = new List<List<int>>
{
new List<int>{ 13,14,15},
new List<int>{ 16,17,18}
}
};
var students = new List<Student> { a, b, c };
var out1 = students
.Select(x => new { Id = x.Id, Sum = x.Data.SelectMany(n => n).Sum() })
.FirstOrDefault(s => s.Id == 1)
.Sum;
var out2 = students
.FirstOrDefault(s => s.Id == 1)
.Data.SelectMany(n => n)
.Sum();
Console.WriteLine(out1);
Console.WriteLine(out2);
Console.ReadLine();
}
}