从lambda表达式

时间:2017-08-30 13:28:42

标签: c# linq lambda

我有这个方法:

 public static SiteSettingEntity 
       GetSettings<SiteSettingEntity>(string siteId, 
                 Expression<Func<SiteSettingEntity, object>> properties)
 {
     // This method returns a SiteSettingEntity
     // filled with the values  selected in my expression
 }

如果想要调用:

var _siteSetting = SiteSettingService.GetSettings<SiteSettingEntity>(SiteID, 
                 s => new { s.BillCycleType, s.InvoiceComment, 
                s.AllowInvoiceDetailApproval, s.JobMinimumHours });

因此,这将返回一个对象,其中填充了由lambda表达式选择的属性。

我的问题是:如何使用我的表达式动态返回自定义对象?

举个例子:如果你想使用.Select(s => new{ filed1 = data.FieldX}),你可以在返回对象中使用属性.filed1

谢谢!

3 个答案:

答案 0 :(得分:1)

如果您尝试返回动态对象,可以执行类似使用ExpandoObject的简单示例:

public class DuckFactory
{
    public ExpandoObject GetDuck()
    {
        dynamic duck = new ExpandoObject();
        duck.Name = "Fauntleroy";
        return duck;
    }
}

然后称之为:

dynamic duck = new DuckFactory().GetDuck();

//  Check the property exists before using it
if (((IDictionary<string, Object>)duck).ContainsKey("Name"))
{                
    Console.WriteLine(duck.Name);   //  Prints Fauntleroy
}
else
{
    Console.WriteLine("Poor duck doesn't have a name.");
}

请记住,您无法获得强类型对象的好处。

答案 1 :(得分:0)

这是我原来的方法:

public static T GetSettings<T>(string siteId, Expression<Func<SiteSettingEntity, object>> properties)
    {
        string query = $"SELECT TOP 1 {DbTool.GetSqlFields(properties)} FROM {SiteSettingEntity.TABLE_NAME} (NOLOCK) WHERE Sites.SiteID = @SiteID";

        var parameters = new Dictionary<string, object>
        {
            {"SiteID", siteId},
        };

        var _data = DbTool.SqlExec<T>(PowerDetailContext.GetConnectionString(siteId), CommandType.Text, query, parameters);

        return _data != null ? _data.FirstOrDefault() : default(T);
    }

当我打电话的时候,我有这个:

var _siteSetting = SiteSettingService.GetSettings<SiteSettingEntity>(SiteID, s => new { s.BillCycleType, s.InvoiceComment, s.AllowInvoiceDetailApproval, s.JobMinimumHours });

var _siteSetting我希望在调用时只在新{}之间使用SELECTED属性。如果我尝试使用_siteSetting。 OtherProperty ,那么&#34; OtherProperty &#34;在代码中无法使用。

答案 2 :(得分:0)

再次阅读之后我想你只是想从GetSettings方法返回SiteSettingEntity。

public static SiteSettingEntity GetSettings<T>(string siteId, Expression<Func<SiteSettingEntity, object>> properties)
    {
        string query = $"SELECT TOP 1 {DbTool.GetSqlFields(properties)} FROM {SiteSettingEntity.TABLE_NAME} (NOLOCK) WHERE Sites.SiteID = @SiteID";

        var parameters = new Dictionary<string, object>
        {
            {"SiteID", siteId},
        };

        var _data = DbTool.SqlExec<SiteSettingEntity>(PowerDetailContext.GetConnectionString(siteId), CommandType.Text, query, parameters);

        return _data != null ? _data.FirstOrDefault() : default(SiteSettingEntity);
    }