One of the great things about LINQ is that allows you to get information that's related to a collection without having to manually write code to iterate through the collection. Is there a way to use LINQ to populate a collection, thus avoiding the need to write a loop?
For example, let's say I have the following code which 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 for
loops that would be required to retrieve information about the data. I'm curious as if LINQ could be used to replace the for
loop that populates data. 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);