Sency
Sency

Reputation: 2878

Take Sum of values in Specific Indexes of an array using Linq

I have an object array as

object[] arr=new object[]
                            {
                                "Kushan",       // Index = 0 ( data Type is String)
                                10,             // Index = 1 ( data Type is double)
                                15,             // Index = 2 ( data Type is double)
                                25,             // Index = 3 ( data Type is double)
                                "yytdhj"        // Index = 4 ( data Type is String)
                                35,             // Index = 5 ( data Type is double)
                                88,             // Index = 6 ( data Type is double)
                                65,             // Index = 7 ( data Type is double)
                                98,             // Index = 8 ( data Type is double)
                                "Address"       // Index = 9 ( data Type is String)
                            };

I wanna take the sum of elements at index 1,2,3,5,6,7,8 Is this possible to do this using linq? if possible how ?


P:S:

Sorry for making you misunderstood, I really wanna take the sum using specific indexs. not looking the data type.

Upvotes: 1

Views: 2616

Answers (2)

Tomas
Tomas

Reputation: 3643

In the example you provided the datatype of the example was infact int, not double. Here is a full, working example using OfType().

 object[] arr=new object[]
                        {
                            "Kushan",       // Index = 0 ( data Type is String)
                            10D,             // Index = 1 ( data Type is double)
                            15D,             // Index = 2 ( data Type is double)
                            25D,             // Index = 3 ( data Type is double)
                            "yytdhj",        // Index = 4 ( data Type is String)
                            35D,             // Index = 5 ( data Type is double)
                            88D,             // Index = 6 ( data Type is double)
                            65D,             // Index = 7 ( data Type is double)
                            98D,             // Index = 8 ( data Type is double)
                            "Address"       // Index = 9 ( data Type is String)
                        };
        var sum = arr.OfType<double>().Sum();

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503469

In this case, you're adding all the double values together. If that's what you're really after, you can use:

var sum = arr.OfType<double>().Sum();

Otherwise, if you really need to use the indexes, you want something like:

var sum = indexes.Select(x => (double) arr[x])
                 .Sum();

(That's assuming you have the indexes in a collection of some kind.)

Upvotes: 5

Related Questions