gpt4 book ai didi

c# - Linq 语法来声明显式类型而不是 var

转载 作者:行者123 更新时间:2023-11-30 20:27:50 25 4
gpt4 key购买 nike

我正在尝试编写一个 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; }
}

最佳答案

首先,当您使用 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();

关于c# - Linq 语法来声明显式类型而不是 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48206462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com