我如何智能地List<int>从一个创建一个IEnumerable<CustomClass>,如果CustomClass有一个类型的属性int,customProperty我希望使用它来创建我的List<int>?
List<CustomClass>我知道我可以通过调用创建一个instance.ToList<CustomClass>();
如何提取属性信息以填充我的列表?这里的最佳做法是什么?
我如何智能地List<int>从一个创建一个IEnumerable<CustomClass>,如果CustomClass有一个类型的属性int,customProperty我希望使用它来创建我的List<int>?
List<CustomClass>我知道我可以通过调用创建一个instance.ToList<CustomClass>();
如何提取属性信息以填充我的列表?这里的最佳做法是什么?
使用 Linq,您可以投影到属性和ToList()结果IEnumerable<int>:
var ints = customClasses.Select(c => c.customProperty).ToList();
如果您以前从未见过 Linq 扩展方法,那么Select这是一种常见的“投影”方法。它需要一个 lambda 表达式,在这种情况下,一个表达式采用CustomClass表示为的类型c,它返回任何你想要的,在这种情况下是一个int. 在Select处理一组(可枚举的东西)时,您实际上会得到IEnumerable<int>响应,它可以IEnumerable根据您的Selectlambda 推断类型。
如果您想要延迟运行IEnumerable<int>,只需挂断ToList()电话。
我从不喜欢就最佳实践发表意见,但这是一个清晰的单行字,清楚地表明了意图(假设对 Linq 有基本的了解),而且我到处都能看到它。
林克资源:
http://www.codeproject.com/Articles/84521/LINQ-for-the-Beginner
http://www.codeproject.com/Articles/19154/Understanding-LINQ-C
Lambda 表达式资源:
http://msdn.microsoft.com/en-us/library/bb397687.aspx
或者,可以使用“LINQ 教程”或“lambda 表达式教程”等术语轻松搜索这些主题。
假设 C# 3.0,因此 LINQ,
var intList = instance.Select(cc => cc.customProperty).ToList();
使用 Linq 投影很容易做到这一点。使用功能符号:
var myEnumerable = new IEnurable<CustomClass>;
// ... fill myEnumerable
List<int> customProperties
= myEnumrable.Select(item => item.customProperty).ToList();
lambda 表达式投影item => item.customPropertyint,因此您得到一个 int 列表。基本上,lambda 表达式相当于一个函数,它item作为参数接收并item.customProperty作为结果返回。类似的东西int foo(CustomaClass item) { return item.customProperty}。lambda 表达式的特殊性在于它是匿名的(没有foo),并且返回和参数类型是从上下文中推断出来的。
选择:
List<int> customProperties
= (from item in myEnumerable
select item.customProperty).ToList();
在这种情况下,投影直接在select子句中完成。所有 LINQ 查询都在括号之间,以允许使用ToList().
在这里,我留下一个代码片段,您可以在其中看到类似查询的所有变体:
public class Thing
{
public string Name { get; set; }
public decimal Value { get; set; }
}
public decimal GetValue(Thing thing)
{
return thing.Value;
}
public Thing[] Things =
{
new Thing { Name="Stapler", Value=20.35M},
new Thing { Name="Eraser", Value=0.65M}
};
[TestMethod]
public void GetValueListFromThing()
{
// query notation, direct projection
List<decimal> valuesA
= (from t in Things
select t.Value).ToList();
// query notation, projection with method
List<decimal> valuesB
= (from t in Things
select GetValue(t)).ToList();
// functional notation, projection with method
List<decimal> valuesC
= Things.Select(t => GetValue(t)).ToList();
// functional notation, projection with anonymous delegate
List<decimal> valuesD
= Things.Select(t => { return t.Value; }).ToList();
// functional notation, lambda expression
List<decimal> values
= Things.Select(t => t.Value).ToList();
}