[Reserved] C # Average method using List averaging respective elements of the collection

List C # in the set operation, sometimes need to be aggregated List averaged collection element, such as a numeric type List collection element, the collection of object types List sometimes also requires an element of the set of objects are aggregated demand average, at this time can be used to implement the average, average Linq extension method List is set, there are two methods average forms, one without any parameters average () form, as is suitable for numeric int , numeric type double, decimal, etc. List set calculates an average value, the other is written with a Lambda expression of the form.

(1) a set of values ​​for the type of List directly Calling an Average () can be realized in the form of, for example, a List <int> List1 set, which elements are 1 to 10, with the following statement averaging

   List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   var avgResutl= list1.Average();

The results calculated as avgResutl = 5.5, avgResult to double double precision.

(2) a case where averaging List according to an attribute of the object set.

E.g. TestModel defined test class class, specifically implemented as follows:

   public class TestModel
    {
         public int Index { set; get; }

        public string Name { set; get; }
    }

A List <TestModel> collection object testList, add to the set of the following three elements is defined.

  List<TestModel> testList = new List<ConsoleApplication1.TestModel>();
            testList.Add(new TestModel()
            {
                 Index=1,
                 Name="Index1"
            });
            testList.Add(new TestModel()
            {
                Index = 2,
                Name = "Index2"
            });
            testList.Add(new TestModel()
            {
                Index = 3,
                Name = "Index3"
            });

Element attributes need Index List set averages aggregated with the following statement:

  var avgResult = testList.Average(t => t.Index);

Last calculated for avgResult = 2, avgResult to double double precision.

 

Note: The text reproduced from personal bloggers station IT technology small fun house , the original link in C # using the Average method List of corresponding elements in the collection averaging technique _IT little fun house .

 

Guess you like

Origin www.cnblogs.com/xu-yi/p/11026475.html