开发者

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

开发者 https://www.devze.com 2023-03-03 00:53 出处:网络
I have an object array as object[] arr=new object[] { \"Kushan\",// Index = 0 ( data Type is String) 10,// Index = 1 ( data Type is double)

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" 开发者_C百科       // 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.


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.)


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消