0

Consider the following:

static void Main(string[] args)
        {
            List<object> someList = new List<object>();
            someList.Add(1); 
            someList.Add(2); 
            someList.Add("apple"); 
            someList.Add(true);
            someList.Add(3);
        }

The list items have not been defined with a data type and contains a boolean, a string, and an integer. Assuming there are many more list items of varying data types, how do I sum only the integers (such as 1, 2, and 3) from the list of objects using a simple loop or if statement? I'm just beginning in C#, thank you!

After searching, I've tried something like this, but with no success:

            if(!someList.Contains(int))
                List.Add(int);
  • Would `long.MaxValue` count as an integer? Would `16m` (i.e. `decimal` type containing an integer value) count? – mjwills Aug 12 '20 at 00:23
  • Out of curiosity, what is the practical application of such list? – CoolBots Aug 12 '20 at 00:26
  • It's a homework question from class. I'm not sure of the application, but then again, I'm very new to programming. – acooldryplace00 Aug 12 '20 at 00:30
  • 1
    The contrived nature of homework questions makes them nearly impossible to answer well, and especially when the author of the question fails to provide any context that would explain what a good answer would be. `List` is a practically useless type of object; if one insists on using it, then any operation that should be applied only to members of a specific type can be done with the `OfType()` method. See duplicate. – Peter Duniho Aug 12 '20 at 00:49

1 Answers1

2

If you know they are boxed int you could use OfType and Sum

var result = someList.OfType<int>().Sum();

Or for anything that is a representation of an int that would convert to a string representation, you could use Sum with ToString, and int.TryParse

var result = someList.Sum(x => int.TryParse(x.ToString(), out var value) ? value : 0);

Or if you like loops

var result = 0;
foreach (var value in someList.OfType<int>())
   result += value;

// or 

var result = 0;
foreach (var item in someList)
   if (int.TryParse(item.ToString(), out var value))
      result += value;

Additional Resources

Enumerable.OfType(IEnumerable) Method

Filters the elements of an IEnumerable based on a specified type.

Enumerable.Sum Method

Computes the sum of a sequence of numeric values.

Int32.TryParse Method

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141