0

Best described with an example, so i'll jump straight into an example model and code below to illustrate my question.

Models:

public class MyModel
{
    public int Id { get; set; }
    public virtual ICollection<MySecondModel> MySecondModels { get; set; }
}

public class MySecondModel
{
    public int Id { get; set; }
    public int Counter { get; set; }
}

In my Controller, i want to get a sum of the Counter from MySecondModel, who all relates to MyModel.

I currently have

var person = await db.Persons.Select(i =>
                new PersonDTO()
                {
                    Id = i.Id,
                    Counter = i.MySecondModels.FirstOrDefault().Counter
                }).SingleOrDefaultAsync(i => i.Id == id);

But this obviously only gets me the value from the first, and not all of them.

Any ideas?

brother
  • 7,651
  • 9
  • 34
  • 58
  • 1
    LINQ provides aggregates similar to those provided by SQL, eg Sum(), Count(), Avg(), Distinct(), Min(), Max() and a general purpose Aggregate() that you can use to create custom aggregates – Panagiotis Kanavos Feb 22 '16 at 15:36
  • 2
    For your next question please try to read [ask]. Searching the web for "C# sum int" yields plenty of results that you can work from. – CodeCaster Feb 22 '16 at 15:37

0 Answers0