[英]Determine if there are n instances of any value in a collection
我有一個List<int>
,其值類似{1,2,1,5,4,4,1},但時間更長。 我想測試列表中是否有n個具有相同值的實例-任何值。 例如,如果我有一個類似bool duplicateCount(int n, IEnumerable<int> collection)
的函數,請使用上面的列表:
repeatCount(4,list); //錯誤
repeatCount(3,list); //是,因為有3個1
過去,我會通過構建Dictionary<int, int>
並計算每個成員的實例來解決此類問題。 但是,為了幫助我學習Linq,我想嘗試使用該技術實施解決方案。
我在下面編寫了一個使用groupby的查詢,但是在獲取每個組中元素的數量時遇到了麻煩。 關於如何進行此處的任何建議?
var q = from i in list group i by i into g select g.Count();
您可以使用GroupBy
,然后檢查Any
組的Count
大於或等於該數字
public bool duplicateCount(int n, IEnumerable<int> collection)
{
return collection.GroupBy(x => x).Any(g => g.Count() >= n)
}
如果要確定是否有任何值正好重復n次,則執行以下操作。
public bool duplicateCount(int n, IEnumerable<int> collection)
{
return collection.GroupBy(x => x).Any(g => g.Count() == n)
}
還有查詢語法,盡管我認為在這種情況下方法語法看起來更好,尤其是因為您無法將Any
轉換為查詢語法。
public bool duplicateCount(int n, IEnumerable<int> collection)
{
return (from item in collection
group by item into grp
select grp.Count()).Any(count => count == n)
}
除了lambda表達式
List<int> list = new List<int>() { 1, 2, 3, 3, 3, 4, 4, 4, 4,2,2,2, 2, 2, 2, 5, 5, 5, 5 };
var q = (from i in list
where i == 2
select i).Count();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.