Home > OS >  Linq for list of objects make a collection of its fields
Linq for list of objects make a collection of its fields

Time:08-15

Can LINQ write this shorter?

class MyClass
{
    public int Field1;
    public int Field2;
}

var src = new List<MyClass>
{
    new MyClass{Field1 = 0, Field2 = 1},
    new MyClass{Field1 = 2, Field2 = 3}
};

var list = new List<int>();
foreach (var item in src)
{
    list.Add(item.Field1);
    list.Add(item.Field2);
}

In the end, list is like this: 0, 1, 2, 3.

CodePudding user response:

Yes, you can put the int values into an array and use SelectMany to flatten the arrays:

var list = src.SelectMany(x => new[] { x.Field1, x.Field2 }).ToList();

For completion, if you want to do this for all public int fields in your class without having to manually specify them, you may use reflection for that:

var fields = typeof(MyClass).GetFields().Where(f => f.FieldType == typeof(int));
var list = src.SelectMany(x => fields.Select(f => (int)f.GetValue(x))).ToList();
  • Related