返回新的LINQ对象 [英] Return new LINQ object
本文介绍了返回新的LINQ对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写LINQ,它返回的新对象(字符串,整数)包含以下内容:
I want to write LINQ which return me new object(string, int) contains:
- 字符串(位置名称)
- int(职位数)
输出:
PositionA 8
PostionB 12
PostionC 13
这是我到目前为止所拥有的:
Here is what I have so far:
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;
}
测试列表具有类似字段:位置,人名,城市,姓氏.所有字段都是 string
.
TestList have fields like: Postion, PersonNR, City, LastName. All the fields are string
.
推荐答案
您可能正在寻找元组
.如果是C#7.3+,则可以尝试使用命名元组:
You, probably, are looking for a Tuple
. In case of C# 7.3+ you can try using named tuples:
https://docs.microsoft.com/zh-cn/dotnet/csharp/tuples
public IEnumerable<(string, int)> TestL() {
return TestList
.GroupBy(s => s.Postion.ToUpper())
.Select(chunk => (NameDisplay: d.Key, Count: d.Count()))
.OrderBy(item => item.NameDisplay);
}
在较旧的C#版本中,未命名之一:
In older C# versions unnamed one:
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(...)
In case you want to return not IEnumerable<T>
but List<T>
, add .ToList()
after .OrderBy(...)
这篇关于返回新的LINQ对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文