对基于 LINQ 的列表使用匿名类型而不是 var

Use anonymous type for LINQ based lists instead of var

我有 LINQ 请求 return 匿名类型,例如:

var result = context.Table1.Select(
    x => new
    {
        col1 = x.col1,
        col2 = x.col2
    }).ToList();

这很好用,直到我想将结果交给另一个函数。

我需要具体说明列表的类型。我不能再使用 var

但是如果我使用

List< (string col1, string col2)> result ...

我收到 “无法隐式转换类型 ...” 错误。

是的,我可以为每个实体创建一个新的 class。但这是唯一的处理方式吗?

如果你想使用元组类型(这就是你的(string col1, string col2))而不是匿名类型(这就是你的 new { col1=x.col1...} ),你需要另一种语法:

List<(string col1, string col2)> list = context.Table1
    .Select( // linq to entities
    x => new
    {
        col1 = x.col1,
        col2 = x.col2
    })
    .ToArray() // go on with linq to objects for use of tuple types
    .Select(x => (col1: x.col1, col2: x.col2))
    .ToList();

表达式树不支持值元组,因此您可能需要在查询中结合使用匿名类型和元组类型

参见Tuple typesChoosing between anonymous and tuple types