Let's say I have a class with two numerical properties and I create a bunch of them.
public class TwoNumbers
{
public TwoNumbers(int first, int second)
{
First = first;
Second = second;
}
public int First { get; set; }
public int Second { get; set; }
}
Is there a way using LINQ or lambda queries to add both First and Second of each object to a list of integers? For example:
List<TwoNumbers> twoNumbersList = new List<TwoNumbers>()
{
new TwoNumbers(1,1),
new TwoNumbers(32,59),
new TwoNumbers(-12,200),
}
// Can I populate a list of integers upon assignment with a LINQ or lambda query?
List<int> integersVerbose = new List<int>()
foreach (var tn in twoNumbersList)
{
integersVerbose .Add(tn.First);
integersVerbose .Add(tn.Second);
}
// Desired syntax
var integersConcise = twoNumbersList. /* some expression */ .ToList(); // Automatically infers type from query
// Print the numbers
integersVerbose.Foreach(x => Console.WriteLine(x));
integersConcise.Foreach(x => Console.WriteLine(x));
// Expected output:
// 1
// 1
// 32
// 59
// -12
// 200
// 1
// 1
// 32
// 59
// -12
// 200
I am aware that there's a SelectMany method but it doesn't seem useful here because I'm not trying to extract a collection from an object, I just want a flat list with numbers.