我想编写LINQ,它返回的新对象(字符串,整数)包含以下内容:
输出:
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
测试列表具有类似字段:位置,人名,城市,姓氏。所有字段均为let t1 ({A=a; B=b} : tmp) =
match b with
| (Some i) -> [{ A = a; B= i}]
| _ -> []
let getGrouped (l: tmp list) =
l |> List.collect t1
|> List.groupBy (fun a -> a.A)
。
答案 0 :(得分:2)
您可能正在寻找Tuple
。如果是C#7.3+,则可以尝试使用命名元组:
https://docs.microsoft.com/en-us/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#版本中,未命名之一:
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(...)
答案 1 :(得分:1)
通过修改更少的代码,您可以实现所需的输出,
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;
}
注意:请确保已在项目中的NuGet软件包下面安装了该软件包,否则您将收到List<(string, int)>
或IEnumerable<(string, int)>
Install-Package "System.ValueTuple"