我有这个问题。有一个字符串
string [5] names = { "John", "Sam", "Harry", "Sam", "John" }
我需要找到数组中最常见的元素。我尝试使用:
string MostCommon = names.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First()
.Key;
不幸的是,它只找到一个元素,即MostCommon = John
,在这种情况下,我不仅需要John
,还需要Sam
。我怎么能这样做?在这种情况下,LINQ不是必需的吗?
答案 0 :(得分:10)
First
显然只会选择序列的第一个元素。但是,您需要具有相同编号的所有组。因此,请选择每个组的名称和编号,然后再订购 。最后选择与第一组具有相同计数的所有组。
var groups = names.GroupBy(x => x)
.Select(x => new { x.Key, Count = x.Count() })
.OrderByDescending(x => x.Count);
int max = groups.First().Count;
var mostCommons = groups.Where(x => x.Count == max);
编辑:您还可以在最后一个语句中使用TakeWhile
而不是Where
,以避免对groups
- 列表中的最后一个元素进行不必要的比较,并在第一个组时立即停止发现元素少于第一个元素:
var mostCommons = groups.TakeWhile(x => x.Count == groups.First().Count);
答案 1 :(得分:5)
这可以按照以下方式完成 -
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'app-book-list',
templateUrl: './book-list.component.html',
styleUrls: ['./book-list.component.css']
})
export class BookListComponent implements OnInit {
books: any;
constructor(private http: Http) { }
ngOnInit() {
this.http.get('/api/books.json')
.subscribe(response => this.books = response.json());
}
}
答案 2 :(得分:4)
根据您找到的最常见名称的数量,将您的第一个LINQ与另一个类似的linq结合起来。
string MostCommon = names.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First();
int count = names.Where(x => x == MostCommon).Count();
var mostCommonList = names.GroupBy(v => v)
.Where(g => g.Count() == count);
答案 3 :(得分:0)
//With Dictionary
//This is more useful if you are looking to interview big companies otherwise use the
Linq option which is short and handy
public static int MaxOccurrenceOfWord(string[] words)
{
var counts = new Dictionary<string, int>();
int occurrences = 0;
foreach (var word in words)
{
int count;
counts.TryGetValue(word, out count);
count++;
//Automatically replaces the entry if it exists;
//no need to use 'Contains'
counts[word] = count;
}
string mostCommonWord = null;
foreach (var pair in counts)
{
if (pair.Value > occurrences)
{
occurrences = pair.Value;
mostCommonWord = pair.Key;
}
}
Console.WriteLine("The most common number is {0} and it appears {1} times",
mostCommonWord, occurrences);
return occurrences;
}