我尝试编写LINQ查询以获取List<List<testobject>> results = ...
我使用var得到了正确的结果但是想要声明显式类型而不是使用var
。这样做的正确语法是什么?
简单示例如下
class Program
{
static void Main(string[] args)
{
List<testobject> testobjectList = new List<testobject>()
{
new testobject(){field1 = 1, field2 = "1",field3 = "1",field4 = "1", field5 = "1"},
new testobject(){field1 = 1, field2 = "1",field3 = "1a",field4 = "1a", field5 = "1a"},
new testobject(){field1 = 1, field2 = "1",field3 = "1b",field4 = "1b", field5 = "1b"},
new testobject(){field1 = 2, field2 = "2",field3 = "2",field4 = "2", field5 = "2"},
new testobject(){field1 = 3, field2 = "3",field3 = "3",field4 = "3", field5 = "3"},
new testobject(){field1 = 4, field2 = "4",field3 = "4",field4 = "4", field5 = "4"},
new testobject(){field1 = 4, field2 = "4",field3 = "4a",field4 = "4a", field5 = "4a"},
new testobject(){field1 = 5, field2 = "5",field3 = "5",field4 = "5", field5 = "5"},
new testobject(){field1 = 6, field2 = "6",field3 = "6",field4 = "6", field5 = "6"},
new testobject(){field1 = 6, field2 = "6",field3 = "6a",field4 = "6a", field5 = "6a"},
new testobject(){field1 = 6, field2 = "6",field3 = "6b",field4 = "6b", field5 = "6b"},
new testobject(){field1 = 7, field2 = "7",field3 = "7",field4 = "7", field5 = "7"}
};
// Correct output
var results1 = testobjectList.Where(x => x.field1 >= 2)
.GroupBy(x => x.field2).ToList();
// But how do I do the same but explicitly state type?
List<List<testobject>> results2 = testobjectList.Where(x => x.field1 >= 2)
.GroupBy(x => x.field2).ToList();
}
}
class testobject
{
public int field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
public string field4 { get; set; }
public string field5 { get; set; }
}
答案 0 :(得分:3)
首先,当您使用GroupBy
函数时,var
将编译为:
List<IGrouping<string,testobject>>
如果您真的想拥有List<List<testobject>>
,可以使用此查询:
testobjectList.Where(x => x.field1 >= 2).GroupBy(x => x.field2).Select(x => x.ToList()).ToList();
如果你想拥有List<testobject>
,你可以使用:
testobjectList.Where(x => x.field1 >= 2).GroupBy(x => x.field2).Select(x => x.First()).ToList();
答案 1 :(得分:1)
当您将鼠标悬停在VisualStudio中的ToList()
调用上时,您会看到返回类型为List<IGrouping<string, testobject>>
尝试:
List<IGrouping<string, testobject>> results2 = testobjectList.Where(x => x.field1 >= 2)
.GroupBy(x => x.field2).ToList();
如果你有ReSharper,你可以使用“明确指定类型”重构将var语句转换为显式类型。
答案 2 :(得分:0)
List<List<testobject>>
不是正确的类型。如果您在一行之后添加断点并且声明了results1
并检查了它的类型,您可能会看到与List<IGrouping<string, testobject>>
类似的内容。如果要声明显式类型,请使用一些方法来确定实际类型,如调试器,IDE或某些插件。 ReSharper可以为您提供重构选项来声明显式类型而不是var
。
答案 3 :(得分:0)
您需要通过添加.SelectMany()来强化您的结果,以便将结果强类型为List。
您还将列表声明为列表&lt; 列表&gt;结果2应该是列表
工作样本:
List<testobject> results2 = testobjectList .Where(x => x.field1 >= 2)
.GroupBy(x=>x.field2)
.SelectMany(x=>x)
.ToList();