var query = from str in strdizi
where str.StartsWith(str.Substring(0, 1))
orderby str
group str by str.Substring(str.LastIndexOf(Convert.ToChar(str.Substring(0, 1))))
into ws
where ws.Count() >= 1
select ws;
foreach (var item in query)
{
Console.WriteLine(item.Key + " " + item.Count());
foreach (var items in item)
{
Console.WriteLine(items);
}
}
但输出是;
安迪1
安迪
亚瑟1亚瑟
我想要;
A - 1
安迪
亚瑟
Ashlynn
感谢您的帮助。索里因为我的英语不好。
答案 0 :(得分:1)
您不需要where
条件,只需按子字符串对数据进行分组即可:
var strdizi = new string [] {"Andy", "Arthur", "Ashlynn", "Ben", "Chris"};
var query = from str in strdizi
group str by str.Substring(0, 1 )
into ws
where ws.Count() >= 1
select ws;
foreach (var item in query)
{
Console.WriteLine(item.Key + " " + item.Count());
foreach (var items in item)
{
Console.WriteLine(items);
}
}
这给出了结果:
A 3
Andy
Arthur
Ashlynn
B 1
Ben
C 1
Chris
答案 1 :(得分:0)
由于我更喜欢方法语法而不是查询语法,因此您可以这样做:
var strdizi = new string [] {"Andy", "Arthur", "Ashlynn", "Ben", "Chris"};
var query = strdizi.GroupBy(g=>g.Substring(0,1));
foreach (var item in query)
{
Console.WriteLine(item.Key + " " + item.Count());
foreach (var items in item)
{
Console.WriteLine(items);
}
}