2016-03-03 29 views
1

我有KeyValuePair的列表,它的值列表過於如清單是不同

List<KeyValuePair<string, List<string>>> ListX = new List<KeyValuePair<string,List<string>>>(); 
ListX.Add(new KeyValuePair<string,List<string>>("a",list1)); 
ListX.Add(new KeyValuePair<string,List<string>>("b",list1)); 
ListX.Add(new KeyValuePair<string,List<string>>("a",list1));` 

我希望每個KeyValuePair列表中的密鑰進行不重複,只有按鍵,可以我在這個列表中使用Distinct?

例如我希望列表中具有「a」鍵的第三個項目因爲重複而被刪除。

+3

使用'Dictionary >'代替。如果密鑰已經存在,則添加方法會引發異常。你可以首先使用'ContainsKey'方法來檢查密鑰是否已經存在。或者您可以使用索引器而不是Add方法,如果密鑰已經存在,它將覆蓋舊值。 'dic [「a」] = list1;' –

回答

1

雖然可以解決與您當前的List製造具有Distinct鍵,我覺得適合你的情況是最簡單的解決方案是使用Dictionary<string,List<string>>

只是恰好你需要的東西:

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); 
dict.Add("a", new List<string>()); 
dict.Add("b", new List<string>()); 
dict.Add("a", new List<string>()); //will throw an error 

圖片:

if (dict.ContainsKey(key)) //the key exists 
+0

這很好,我沒有一個想法,字典可以有超過1個item.thank你 – user1947393

0

您可以使用繼承自IEnumerable<KeyValuePair<TKey, TValue>>Dictionary<TKey, TValue>類。它是KeyValuePairs的一個集合,它只允許唯一的鍵。

+0

如果我試圖添加重複密鑰,它會給我一個錯誤?對吧?我不希望出現錯誤,我希望它可以防止在沒有錯誤的情況下添加錯誤 – user1947393

+0

@ user1947393只需在插入項目前添加一個檢查項'if(!d.ContainsKey(key))' –

0

U可以使用

Dictionary<TKey, TValue> 

其中TKEY和Tvalue是通用的數據類型。

例如它們可以是整型,字符串,另一個詞典等

Dictionary<int , string>, Dictionary<int , List<employee>>

在所有這些情況下,關鍵是獨特部分即,相同的鍵不能被再次插入。

U可以檢查是否使用鮮明這樣即使ü嘗試添加相同的密鑰

然而鮮明只能防止相同的鍵值對沒有異常發生存在關鍵。

防止相同的密鑰被添加使用Enumerable.GroupBy
ListItems.Select(item => { long value; bool parseSuccess = long.TryParse(item.Key, out value); return new { Key = value, parseSuccess, item.Value }; }) .Where(parsed => parsed.parseSuccess) .GroupBy(o => o.Key) .ToDictionary(e => e.Key, e => e.First().Value)

+0

此代碼將添加第一個「a」作爲鍵和List。您不能將相同的密鑰「a」添加到字典中,這是添加字典的唯一目的。 –

0

enter image description here

如果需要檢查,如果一個Key當你想一個<Key,Value>添加到您的字典,只需ContainsKey檢查已經存在

List<Dictionary<int, List<int>>> list = new List<Dictionary<int, List<int>>>(); //List with a dictinary that contains a list 
int key = Convert.ToInt32(Console.ReadLine()); // Key that you want to check if it exist in the dictinary 
int temp_counter = 0; 

foreach(Dictionary<Int32,List<int>> dict in list) 
{ 
    if(dict.ContainsKey(key)) 
    temp_counter+=temp_counter; 
} 

if (temp_counter == 0) // key not present in dictinary then add a to the list a dictinary object that contains your list 
{ 
    Dictionary<int,List<int>> a = new Dictionary<int,List<int>>(); 
    a.Add(key,new List<int>()); // will contain your list 
    list.Add(a); 
} 

檢查是否有效

1
var dictionaryX = ListX 
    .GroupBy(x => x.Key, (x, ys) => ys.First()) 
    .ToDictionary(x => x.Key, x => x.Value); 

我不確定這是否是您要查找的內容,但它是通過僅爲每個重複鍵獲取第一個值將ListX轉換爲字典的查詢。