简体   繁体   English

建立清单 <T> T是在C#中使用LINQ的匿名类型

[英]Create a List<T> with T being an anonymous type using LINQ in C#

Let's say we have the List<Item> data , and the Item class is defined as below: 假设我们有List<Item> data ,并且Item类的定义如下:

public class Item
{
    public double Station { get; set; }
    public double Area { get; set; }

    ...
    // other properties present in the class

}

Now how can we create a new List<T> out of List<Item> , so that T is anonymous type having only double Station and double Area as its properties. 现在,我们如何从List<Item>创建一个新的List<T> ,以使T是仅具有double Stationdouble Area作为其属性的匿名类型。

I know how to extract all of the station and area values into a List<double> data2 but what I want above is different. 我知道如何将所有测站和区域值提取到List<double> data2但是我上面想要的是不同的。

var data2 = data
    .SelectMany(x => new[] { x.Station, x.Area })
    .ToList();

I think what you need is... 我认为您需要的是...

var data2 = data
    .Select(x => new { x.Station, x.Area })
    .ToList();

You don't need SelectMany here, usually it is used to flatten the hierarchy. 您在这里不需要SelectMany ,通常它用于展平层次结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将匿名类型转换为列表 <T> 在C#中使用Linq到SQL - Convert Anonymous Type to List <T> using Linq to SQL in C# 我们可以将匿名类型转换为列表吗 <T> 在C#中使用Linq实体? - Can we Convert Anonymous Type to List <T> using Linq to entity in C#? 为什么我不能在C#中创建一个匿名类型的列表<T>? - why can't I create a list<T> of anonymous type in C#? 通过清单 <anonymous type> 到需要List的方法 <T> 在C#中 - Pass List<anonymous type> into method requiring List<T> in C# 名单 <T> LINQ Projection to Anonymous或Dynamic类型 - List<T> LINQ Projection to Anonymous or Dynamic type 是否可以在C#中的LINQ扩展方法中创建匿名类型? - Is it possible to create anonymous type in LINQ extension methods in C#? 如何将匿名类型转换为列表 <dynamic> 在C#中使用Linq到SQL - How to Convert Anonymous Type to List <dynamic> using Linq to SQL in C# 分组列表时,如果键与您的类型T是同一类型,如何在C#中使用LINQ查询进行分组<T> - How to GroupBy using LINQ query in C# when the key is to be the same type as your type T when grouping List<T> 在联接C#WPF Linq中使用类而不是匿名类型 - Using classes instead of anonymous type in join C# WPF Linq 提取List的两个属性 <T> 在C#中使用LINQ - Extract two properties of a List<T> using LINQ in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM