Home > Mobile >  how to refer to an object variable as an arguemnt in c#
how to refer to an object variable as an arguemnt in c#

Time:12-08

i have multiple lists in a class. I want to get a total for an int argument in a function. I have 3 lists that have same variables, how can i refer to each one and add it to a total without many for each loops?

For example

public int getCalories(string name, ref int argument)
{
    int total = 0;
    foreach (var item in list)
    {
        total  = item.argument;
    }
    foreach (var item in list2)
    {
        total  = item.argument;
    }
   foreach (var item in list3)
    {
        total  = item.argument;
    }
    return total;
}

CodePudding user response:

I don't know what your parameter name is used for, so you should remove it.

If your code above works, i think you can use linq' Sum method to get your result. https://learn.microsoft.com/fr-fr/dotnet/api/system.linq.enumerable.sum?view=net-7.0

public int getCalories(ref int argument)
    => list.Sum(x => x.argument)   list2.Sum(x => x.argument)   list3.Sum(x => x.argument);

CodePudding user response:

If the lists contain the same type you can create an array and then use Enumerable.Sum:

int totalSum = new[]{ list1, list2, list3 }.Sum(list => list.Sum(x => x.argument));

If they contain different types where each have a property int argument use:

int totalSum = list1.Select(x => x.argument)
    .Concat(list2.Select(x => x.argument))
    .Concat(list3.Select(x => x.argument))
    .Sum(); 
  • Related