使用 CustomClass 类型的属性创建列表 IEnumerable

本文关键字:CustomClass IEnumerable 列表 属性 类型 使用 创建 | 更新日期: 2023-09-27 18:31:25

如果CustomClass有一个类型为 int 的属性,称为 customProperty,我希望用它来创建我的List<int>,我如何从IEnumerable<CustomClass>智能地创建一个List<int>

我知道我可以通过调用instance.ToList<CustomClass>();来创建List<CustomClass>

如何提取属性信息以填充我的列表?这里的最佳实践是什么?

使用 CustomClass 类型的属性创建列表 IEnumerable<CustomClass>

使用 Linq,可以投影到属性并ToList()生成的IEnumerable<int>

var ints = customClasses.Select(c => c.customProperty).ToList();

如果您以前从未见过 Linq 扩展方法,Select是一种常见的"投影"方法。它需要一个lambda表达式,在这种情况下是一个表达式,CustomClass表示为c的类型,它返回您想要的任何内容,在本例中为int。当Select正在处理一个集合(可枚举的东西)时,您实际上会得到一个IEnumerable<int>作为响应,它可以根据您的Select lambda 推断IEnumerable的类型。

如果您想要一个延迟运行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();

lambada 表达式item => item.customProperty投影 int,因此您可以获得 int 的列表。 基本上,lambda 表达式等效于一个函数,它接收item作为参数并返回item.customProperty作为结果。像int foo(CustomaClass item) { return item.customProperty}.lambda 表达式的特殊性在于它是匿名的(没有foo),并且返回和参数类型是从上下文推断出来的。

Lambda 表达式(C# 编程指南)

另类:

 List<int> customProperties
   = (from item in myEnumerable
      select item.customProperty).ToList();

在这种情况下,投影直接在select子句中完成。所有 LINQ 查询都在 parethes 之间,以允许使用 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();
    }