我想你需要的東西是這樣的:
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists.ToDictionary(c => c.Key, c => c.Value.Distinct().ToList());
這將項目複製到一個新的字典,只取一個每個項目的副本中值列表。
所以,如果dupeLists
樣子:
{
"first": ["1", "2", "3", "1"],
"second": ["2", "3", "4", "3"]
}
那麼這將返回:
{
"first": ["1", "2", "3"],
"second": ["2", "3", "4"]
}
,你的代碼沒有工作,因爲它是尋找獨特名單相比,內唯一值那些列表。因爲每個列表在內存中都是不同的地方(你知道這是因爲修改一個不會修改另一個),因此調用所產生的每個組只有一個元素長。
原來的問題是更清楚比現在,所以我包括幾個變化,以確保正確的答案被發現。下面列出了後人的名字,但他們證明不適用這種特殊情況。
和公正的好辦法,你said you need to「擺脫重複值的」,這是不明確的。如果你想扔掉任何有任何重複,
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists.ToDictionary(c => c.Key, c => c.Value.GroupBy(x => x)
.Where(x => x.Count() == 1)
.Select(x => x.Key)
.ToList());
將返回:
{
"first": ["2", "3"],
"second": ["2", "4"]
}
而且因爲你抓住了我在一天下來,如果你真的想返回不同項目的平面列表,
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists.SelectMany(c => c.Value).Distinct().ToList();
其產生:
["1", "2", "3", "4"]
還是隻,只有在整個辭典中出現一次:
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists
.SelectMany(c => c.Value)
.GroupBy(c => c)
.Where(c => c.Count() == 1)
.Select(c => c.Key)
.ToList();
那就是:
["4"]
或者只是那些只出現在任何給定列表,但不包括其他人:
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists
.SelectMany(c => c.Value, (kvp, Value) => new { kvp.Key, Value })
.GroupBy(c => c.Value)
.Where(c => c.Select(x => x.Key).Distinct().Count() == 1)
.GroupBy(c => c.Key, c => c.Value)
.ToDictionary(c => c.Key, c => c.ToList());
這是,如果我未測試的代碼可容納:
{
"first": ["1", "1"],
"second": ["4"]
}
你讀心術? :D – dotctor
@dotctor不,但我確實在互聯網上玩過一個。 –
@Matthew - 非常感謝 - 閱讀我的想法(我的錯誤是問這樣一個模糊的問題),謝謝你回答我的第一個問題在這個網站上.. :) – sst