0

I would like to get the sum of the val field.

// member method 
public T sum()
{
    sum = default(T);
    int i = 0;
    while (i < size)
        sum += val[i++];
}

private int size = 0;
private int usedSize = 0;
private T[] val = null;
6
  • 1
    is it possible to add more information Commented May 5, 2016 at 23:02
  • 1
    Trying to do math on values with generic type doesn't work out so well, there are work-arounds but they're all varying degrees of bad. What are you doing with this? Maybe it can be avoided? Commented May 5, 2016 at 23:06
  • I want to get the sum of the list, i just switched from c++ to c# Commented May 5, 2016 at 23:07
  • 2
    You can't do that; The compiler doesn't know that it is possible to add T together. See stackoverflow.com/questions/8122611/… Commented May 5, 2016 at 23:08
  • I think you can do that with Linq without needing to implement any function. msdn.microsoft.com/en-us/library/… . Altought it seems you need to pass a parameter, you don't because it is an extension method (notice the this word on the parameter). So instead of writing Sum(Collection), you write Collection.Sum(). Commented May 5, 2016 at 23:14

1 Answer 1

1

Here are some worked examples, using System.Linq;

void Main()
{
    List<int> numbers = Enumerable.Range(1,100).ToList();
    var result = numbers.Sum();
    Console.WriteLine(result); // Prints 5050
    List<SomeType> customTypeList = Enumerable.Range(1, 100).Select(x => new SomeType { SomeVal = x}).ToList();
    var customResult = customTypeList.Sum(n => n.SomeVal);
    Console.WriteLine(result); // Prints 5050
}

public class SomeType
{
    public int SomeVal { get; set;}
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think this wont solve my problem , anyway thank you all

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.