Is there a way to populate a collection using a LINQ expression?

One of the great things about LINQ is that you can get information related to the collection without having to manually write code to iterate through the collection. Is there a way to use LINQ to populate a collection, thereby avoiding the need to write a loop?


For example, let's say I have the following code that works with a range of numbers from one to ten:

public static void LinqTest()
{
    List<int> intList = new List<int>();
    for (int i = 1; i <= 10; i++)     //  <==== I'm having to use a for loop
        intList.Add(i);               //        here to populate the List.
    int intSum = intList.Sum();
    int intSumOdds = intList.Where(x => x % 2 == 1).Sum();
    double intAverage = intList.Average();
    Console.WriteLine("Sum is {0}\tSum of Odds is {1}\tAverage is {2}", 
        intSum, intSumOdds, intAverage);
}

LINQ is already replacing the loops it takes forto get data information. I'm curious that LINQ can be used to replace a loop forthat fills . Is there a way to use LINQ to replace the following two lines of code?

    for (int i = 1; i <= 10; i++)
        intList.Add(i);
+3
4

, Enumerable.Range(int, int) , IEnumerable<int>.

List<int> , , , List<T>.

. :

IEnumerable<int> intList = Enumerable.Range(1, 10);
int intSum = intList.Sum();
int intSumOdds = intList.Where(x => x % 2 == 1).Sum();
double intAverage = intList.Average();

, , Enumerable.Range, "", . , List<int>, .

+4

LINQ; Enumerable, . ,

IList<int> intList = Enumerable.Range(1, 10).ToList();
+4

, , , Enumerable.Range(). , , , Where .. , , , , 100, - Enumerable.Range(1,100).Where(i => i * i < 100). , Haskell, : filter (\i -> i * i < 100) [1..100]

:

Enumerable.Range(1,10).Where(x => x%2 == 1).Sum();
//add separate sum and averages here
+2

List<T>has a constructor that takes a parameter IEnumerable<T>as a parameter. You can use Enumerable.Rangeto create numbers.

List<int> values = new List<int>(Enumerable.Range(1, 10));

If you want to add values ​​to a previously built one List<T>, you can use the List<T>.AddRangesame way:

values.AddRange(Enumerable.Range(1, 10));
0
source

Source: https://habr.com/ru/post/1727838/


All Articles