LINQ中的Count,orderby和group(Count, orderby and group in LINQ)
给定一套
巴黎纽约伦敦纽约巴黎巴黎
我正在尝试做一个LINQ查询,该查询将返回巴黎,纽约和伦敦的分组及其各自的计数 。
我已经能够在每个分组中做一个返回仅包含巴黎/纽约/伦敦的组的GroupBy。
听起来比较简单,但我不能让它起作用?
编辑 :这不是一个家庭作业问题。
Given a set
Paris New York London New York Paris Paris
I'm trying to do a LINQ query that will return a grouping of the Paris, New York, and London with their respective counts.
I've been able to do a GroupBy that returns a group containing only the Paris/New York/London in each Grouping.
Sounds relatively simple, but I can't get it to work?
Edit: It's not a homework problem.
最满意答案
码
String[] input = new [] { "Paris", "New York", "London", "New York", "Paris", "Paris" }; var groups = input .GroupBy(city => city) .Select(group => new { City = group.Key, Count = group.Count() }); foreach(var group in groups) { Console.WriteLine("{0} occurs {1} time(s).", group.City, group.Count); }OUTPUT
Paris occurs 3 time(s). New York occurs 2 time(s). London occurs 1 time(s).CODE
String[] input = new [] { "Paris", "New York", "London", "New York", "Paris", "Paris" }; var groups = input .GroupBy(city => city) .Select(group => new { City = group.Key, Count = group.Count() }); foreach(var group in groups) { Console.WriteLine("{0} occurs {1} time(s).", group.City, group.Count); }OUTPUT
Paris occurs 3 time(s). New York occurs 2 time(s). London occurs 1 time(s).更多推荐
发布评论