作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一个 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/
通常当我请求线程转储时,系统性能不佳的症状很容易解释;也就是说,通常我会看到许多线程显然正在等待一个已被获取但未被另一个释放的监视器。 在这种情况下,我有很多线程在等待监视器 (0x965ad100)
C:\Users\shagy\Desktop\3RD YEAR 2ND SEMESTER\SPM\Newfolder\SPM-SMS>npm start npm ERR! path C:\Users\
我是一名优秀的程序员,十分优秀!