Rifat Murtuza
Rifat Murtuza

Reputation: 119

List value return in C#

Hello I have compared two list value and if one list value is greater than other I increment that value +1. Similar to Other.

Finally again add that 2 list value one List value and want to return but got error Like these

solution.cs(42,17): error CS1502: The best overloaded method match for System.Collections.Generic.List<int>.Add(int)' has some invalid arguments /usr/lib/mono/4.6-api/mscorlib.dll (Location of the symbol related to previous error) solution.cs(42,21): error CS1503: Argument #1' cannot convert System.Collections.Generic.List<int>' expression to typeint' solution.cs(43,19): error CS1502: The best overloaded method match for System.Collections.Generic.List<int>.Add(int)' has some invalid arguments /usr/lib/mono/4.6-api/mscorlib.dll (Location of the symbol related to previous error) solution.cs(43,23): error CS1503: Argument#1' cannot convert System.Collections.Generic.List<int>' expression to typeint' Compilation failed: 4 error(s), 0 warnings

Here is my code

int sum_a = 0, sum_b = 0;
for (int i = 0; i < a.Count; i++)
{
    if (a[i] > b[i])
    {
        sum_a++;
    }
    else if (a[i] < b[i])
    {
        sum_b++;
    }
}

List<int> ab = new List<int>();
ab.Add(sum_a);
List<int> ba = new List<int>();
ba.Add(sum_b);

List<int> List = new List<int>();

List.Add(ab);
List.Add(ba);
return List;
//return new List<int>> { sum_a, sum_b };

Please help me how to return these list in C#

Upvotes: 0

Views: 342

Answers (2)

Alain Elemia
Alain Elemia

Reputation: 108

Like @ManishM said, you can't add a List to a List. You can use AddRange in that.

Or based on your scenario, you can just use this:

List<int> sumList = new List<int>{ sum_a, sum_b };

Upvotes: 0

ManishM
ManishM

Reputation: 593

You cannot insert a List in another List this way. For that, AddRange is used

int sum_a=0,sum_b=0;
for(int i=0; i<a.Count; i++)
{
    if(a[i]>b[i])
    {
        sum_a++;
    }
    else if(a[i]<b[i])
    {
        sum_b++; 
    }
}

List<int> ab = new List<int>();
ab.Add(sum_a);
List<int> ba = new List<int>();
ba.Add(sum_b);

List<int> List = new List<int>();
List.AddRange(ab);
List.AddRange(ba);

return List;

Upvotes: 3

Related Questions