我有一本大概像這樣的字典:
{ 1, Value1 }
{ 2, Value1 }
{ 3, Value1 }
{ 4, Value1 }
{ 5, Value2 }
{ 6, Value2 }
{ 7, Value2 }
{ 8, Value3 }
{ 9, Value3 }
{ 10, Value3 }
{ 11, Value3 }
{ 12, Value3 }
{ 13, Value3 }
我試圖找到一種方法,使用 LINQ 或其他方式來隔離最多的重復項。例如,在這種情況下,它將是 Value3 - 我試圖獲得它被復制的次數。
到目前為止,我的進展包括以下實作,所以我想知道是否有更好的方法:
var SortedDict = OriginalDict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
//Deduce the most common duplicate
var List1 = SortedDict.Values.ToList().FindAll(x => x == "Value1");
var List2 = SortedDict.Values.ToList().FindAll(x => x == "Value2");
var List3 = SortedDict.Values.ToList().FindAll(x => x == "Value3");
int MostCommon = new List<int>() { List1.Count, List2.Count, List3.Count }.Max();
在這種情況下,我的預期結果是 6(Value3)。Value2 為 3,Value1 為 4。
我看到的另一個問題是,如果有相同數量的重復 - 在這種情況下最好
uj5u.com熱心網友回復:
嘗試以下:
Dictionary<int, string> dict = new Dictionary<int, string>()
{
{ 1, "Value1" },
{ 2, "Value1" },
{ 3, "Value1" },
{ 4, "Value1" },
{ 5, "Value2" },
{ 6, "Value2" },
{ 7, "Value2" },
{ 8, "Value3" },
{ 9, "Value3" },
{ 10, "Value3" },
{ 11, "Value3" },
{ 12, "Value3" },
{ 13, "Value3" }
};
var results = dict
.GroupBy(x => x.Value)
.Select(x => new { value = x.Key, count = x.Count() })
.OrderByDescending(x => x.count)
.FirstOrDefault();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/498013.html
