In a C # list, how do I select all columns + several custom columns so that in each row all columns are flat (not nested)?

I have a simple Listone that each row has 50 columns . I want to return all 50 columns + 3 custom columns, but I want to make each row of the list as a flat (not nested) object.

Example:

var newList = list.Select(x => new 
    {  x,
       d.CustomColA = x.ColA+10,
       d.CustomColB = x.ColB+30,
       d.CustomColC = x.ColC+50
    });

Result: It works fine , but each line of the result is like a nested object:

var row = newList.FirstOrDefault();
row.x.ColA
row.x.ColB
row.x.ColC
.....
row.CustomColA 
row.CustomColB 
row.CustomColB 

Expected Result:

var row = newList.FirstOrDefault();
row.ColA
row.ColB
row.ColC
.....
row.CustomColA 
row.CustomColB 
row.CustomColB 

I used the type dynamicand wrote the following code, but it did not return the expected result:

var newList = list.Select(x =>
{
   dynamic d = x;
   d.CustomColA = x.ColA+10;
   d.CustomColB = x.ColB+30;
   d.CustomColC = x.ColC+50;
   return d;
   //return x;
});

Result in the watch panel: 'newList.FirstOrDefault()' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'


Update:

: , 50 , , , Select! ( , 53 Select!). .

2: , , , . , . .

+4
3

, , . , Automapper - . . :

:

  • 50 Cols
  • Cols


public class CustomColumns : Cols
{
    public int CustomColA { 
        get{
            return this.ColA + 10;
        }
    }
    public int CustomColB { 
        get{
            return this.ColB + 30;
        }
    }
    public int CustomColC { 
        get{
            return this.ColC + 50;
        }
    }
    public CustomColumns(Cols cols)
    {
        string[] localNames = this.GetType().GetMembers().Where(m => m.MemberType == MemberTypes.Property).Select(m => m.Name).ToArray();
        string[] ctorNames = cols.GetType().GetMembers().Where(m => m.MemberType == MemberTypes.Property).Select(m => m.Name).ToArray();
        string[] names = localNames.Intersect(ctorNames).ToArray();
        foreach (string s in names)
        {
            PropertyInfo propSet = this.GetType().GetProperty(s);
            PropertyInfo propGet = typeof(Cols).GetProperty(s);
            propSet.SetValue(this, propGet.GetValue(cols, null));
        }
    }
}

dotnetfiddle: https://dotnetfiddle.net/AKPYQD

+1

Select:

var newList = list.Select(x => 
    new
    {
       ColA = x.ColA,
       ColB = x.ColB,
       ColC = x.ColC,
       CustomColA = x.ColA+10;
       CustomColB = x.ColB+30;
       CustomColC = x.ColC+50;
    }).ToList();
-2

.Select()creates a new object. Even if you just wrote:

var newList = list.Select(x => new 
{  x  });

You have a nested property. You just need to explicitly assign a new property to each column (do you really need all 50 of them?)

-3
source

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


All Articles