我想编写LINQ,它返回给我新的对象(string,int)包含:
输出:
PositionA 8
PostionB 12
PostionC 13
这是我到目前为止:
public List<string, int> TestL() //or IEnumerable?
{
var q1 = TestList.GroupBy(s => s.Postion.ToUpper())
.Select(d =>
{
return new
{
NameDisplay = d.Key,
Count = d.Count(s => s.PersonNR)
};
})
.OrderBy(g => g.Key);
return q1;
}
TestList包含以下字段:Position,PersonNR,City,LastName。所有的领域都是qazxsw poi。
你可能正在寻找一个string
。对于C#7.3+,您可以尝试使用命名元组:
Tuple
https://docs.microsoft.com/en-us/dotnet/csharp/tuples
在较旧的C#版本中未命名的一个:
public IEnumerable<(string, int)> TestL() {
return TestList
.GroupBy(s => s.Postion.ToUpper())
.Select(chunk => (NameDisplay: d.Key, Count: d.Count()))
.OrderBy(item => item.NameDisplay);
}
最后,您可以实现自定义类:
public IEnumerable<Tuple<string, int>> TestL() {
return TestList
.GroupBy(s => s.Postion.ToUpper())
.Select(chunk => Tuple.Create(d.Key, d.Count()))
.OrderBy(item => item.Item1);
}
如果你想要返回不是 public class MyClass {
public MyClass(string nameDisplay, int count) {
NameDisplay = nameDisplay;
Count = count;
}
public string NameDisplay {get; private set;}
public int Count {get; private set;}
}
...
public IEnumerable<MyClass> TestL() {
return TestList
.GroupBy(s => s.Postion.ToUpper())
.Select(chunk => new MyClass(d.Key, d.Count()))
.OrderBy(item => item.NameDisplay);
}
而是IEnumerable<T>
,请在List<T>
之后添加.ToList()
通过修改较少的代码,您可以实现所需的输出,如,
.OrderBy(...)
注意:确保您已在项目中安装NuGet包下面,否则您将收到public List<(string, int)> TestL() //or IEnumerable?
{
var q1 = TestList.GroupBy(s => s.Postion.ToUpper())
.Select(d =>
{
return new
{
NameDisplay = d.Key,
Count = d.Count()
};
})
.OrderBy(g => g.NameDisplay)
.Select(x => (x.NameDisplay, x.Count))
.ToList();
return q1;
}
或List<(string, int)>
的错误
IEnumerable<(string, int)>