我是泛型的新手,但我知道我需要使用它们来帮助保持 DRY :)
我正在尝试创建一个类,将许多不同类型的列表转换为下拉列表控件使用的通用类,但无法使其工作。我在下面的方法中展示了 2 个选项,尝试让每个选项都起作用(一个 foreach 循环和一个 linq),但无济于事。
private static IEnumerable<ddlOptions> GetDDLOptionsViewModel<T>(List<T> genericList, string strPropName)
{
// option A: ForEach loop
Type type = genericList.GetType();
var IdProperty = type.GetProperty("Id");
var DisplayNameProp = type.GetProperty(strPropName);
List<ddlOptions> options = new List<ddlOptions>();
foreach (var l in genericList)
{
options.Add(new ddlOptions
{
Id = IdProperty.GetValue(l, null),
DisplayName = DisplayNameProp.GetValue(l, null)
});
}
return options;
// option B - LINQ
return from l in genericList
select new ddlOptions
{
Id = l.Id,
DisplayName = l.strPropName
};
}
最佳答案
您可以使用接口(interface)来约束 T
包括 Id
属性(property),你可以使用 Func<T,string>
在保持类型安全和避免反射的同时访问类型 T 对象的任何给定属性:
public interface IId
{
string Id {get;}
}
private static IEnumerable<ddlOptions> GetDDLOptionsViewModel<T>
(IEnumerable<T> list, Func<T,string> propAccess)
where T:IId
{
return list.Select(l => new DdlOption
{
Id = l.Id,
DisplayName = propAccess(l)
});
}
关于c# - LINQ Select() 或 ForEach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13945317/