LINQ : Dynamic select

前端 未结 10 727
北荒
北荒 2020-11-22 05:26

Consider we have this class :

    public  class Data
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field         


        
10条回答
  •  余生分开走
    2020-11-22 05:53

    Another approach I've used is a nested ternary operator:

    string col = "Column3";
    var query = table.Select(i => col == "Column1" ? i.Column1 :
                                  col == "Column2" ? i.Column2 :
                                  col == "Column3" ? i.Column3 :
                                  col == "Column4" ? i.Column4 :
                                  null);
    

    The ternary operator requires that each field be the same type, so you'll need to call .ToString() on any non-string columns.

提交回复
热议问题