使用任何类动态创建Func <t,tr> C#

时间:2018-07-27 08:42:23

标签: c# linq lambda

以下是我的代码,我将数据表转换为类列表

       var cities = ds.Tables[0].AsEnumerable().Select(c => new City
                {
                    CityCode = c.Field<object>("CITY_CODE"),
                    CityMid = c.Field<object>("CITY_MID"),
                    CityName = c.Field<object>("CITY_NAME"),
                    CountryCode = c.Field<object>("COUNTRY_CODE"),
                    StateCode = c.Field<object>("STATE_CODE"),
                    ActiveFlag = c.Field<object>("ACTIVE_FLG"),

                }).ToList();

我的问题是如何使.Select()参数动态化

c => new City     {
                    CityCode = c.Field<object>("CITY_CODE"),
                    CityMid = c.Field<object>("CITY_MID"),
                    CityName = c.Field<object>("CITY_NAME"),
                    CountryCode = c.Field<object>("COUNTRY_CODE"),
                    StateCode = c.Field<object>("STATE_CODE"),
                    ActiveFlag = c.Field<object>("ACTIVE_FLG"),

                }

我知道我必须返回表达式,但是我不明白该如何使用任何类?

2 个答案:

答案 0 :(得分:3)

数据类型为Func<DataRow, City>,该函数采用DataRow并返回City

public IEnumerable<City> GetCities(Func<DataRow, City> selector)
{
    return ds.Tables[0].AsEnumerable().Select(selector).ToList();
}

那样称呼它
var cities = GetCities(c => new City     
{
    CityCode = c.Field<object>("CITY_CODE"),
    CityMid = c.Field<object>("CITY_MID"),
    CityName = c.Field<object>("CITY_NAME"),
    CountryCode = c.Field<object>("COUNTRY_CODE"),
    StateCode = c.Field<object>("STATE_CODE"),
    ActiveFlag = c.Field<object>("ACTIVE_FLG"),
});

或使用上述类型的另一个变量:

Func<DataRow, City> myfunc = c => new City     
{
    CityCode = c.Field<object>("CITY_CODE"),
    CityMid = c.Field<object>("CITY_MID"),
    CityName = c.Field<object>("CITY_NAME"),
    CountryCode = c.Field<object>("COUNTRY_CODE"),
    StateCode = c.Field<object>("STATE_CODE"),
    ActiveFlag = c.Field<object>("ACTIVE_FLG"),
};

var cities = GetCities(myfunc);

如果您的课程不仅是City,而且是不同的课程,则可以使用泛型:

public IEnumerable<T> GetCities(Func<DataRow, T> selector)
{
    return ds.Tables[0].AsEnumerable().Select(selector).ToList();
}

答案 1 :(得分:0)

  

我知道我必须返回表达式,但是我不明白该如何使用任何类?

c => new City { ... }是类型delegate的{​​{1}},在某种程度上等效于获取Func<DataRow, City>并返回DataRow的Method。因此,您可以为其创建方法。

City

,然后将该方法传递给City ConvertToCity(DataRow row) => new City { CityCode = row.Field<object>("CITY_CODE"), CityMid = row.Field<object>("CITY_MID"), CityName = row.Field<object>("CITY_NAME"), CountryCode = row.Field<object>("COUNTRY_CODE"), StateCode = row.Field<object>("STATE_CODE"), ActiveFlag = row.Field<object>("ACTIVE_FLG"), }; 函数:

Select