Select column based on variable in LINQ to SQL

前端 未结 5 1569
眼角桃花
眼角桃花 2021-01-19 03:43

I\'m using LINQ to SQL in C# in my application. I need to be able to select a column of a row, depending upon a variable. This is easy for the row as it\'s a simple where cl

5条回答
  •  感动是毒
    2021-01-19 04:34

    Say the class that holds the permissions is named Permission, you can define an extension method:

    public static class PermissionExtensions
    {
        public static object SelectProperty(this Permission obj, string variable)
        {
            return obj.GetType().GetProperty(variable).GetValue(obj, null);
        }
    }
    

    You can use this in your query like this:

    (from s in dc.Permissions where s.dashboardname == permission select s)
        .Single().SelectProperty(variable);
    

    This doesn't select the property in the query but instead gets it from the instance.

提交回复
热议问题