2017-10-18 45 views
1

如何爲每個不同的鍵添加唯一的編號?最後,我想要一個不同密鑰的「集合」,但每個密鑰也應該有一個值,例如,在current_index_of_collection + 1個創建一個唯一的字典並添加自動遞增的整數值

elements.SelectMany(p => p.Properties.Keys).Distinct(); 

輸出樣本:

Key value 
a 1 
b 2 
c 3 
d 4 
+0

我猜你已經有鑰匙存儲在某個地方? –

+0

這些鍵位於每個元素的properties.keys集合中。我需要添加不斷增加的整數值作爲數據庫id(unique/autoinc) – Elisabeth

+0

如果您想要一個唯一的自動增量數據庫ID,最好使用數據庫內置的自動增量機制。否則,你可能會冒險得到錯誤的值(特別是如果你在不同的線程或簡單的多次運行代碼)。 –

回答

1

您是否在尋找Select((value, index) => ...)

https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx

var dictionary = elements 
    .SelectMany(p => p.Properties.Keys) 
    .Distinct() 
    .Select((key, index) => new { 
    key = key, 
    value = index + 1, 
    }) 
    .ToDictionary(item => item.key, item => item.value); 

或者

var array = elements 
    .SelectMany(p => p.Properties.Keys) 
    .Distinct() 
    .Select((key, index) => new KeyValuePair<MyKeyType, int>(key, index + 1)) 
    .ToArray(); 
+0

hm我甚至用Select的索引超載有點困惑。謝謝,我最喜歡你的解決方案,因爲它包含ToDictionary()中的所有內容, – Elisabeth

1

可以使用Select超載它有一個索引字段:

string[][] elements = new string[][] { new string[] { "a", "b", "a" } }; 
var elementsWithIndex = elements.SelectMany(p => p) 
           .Distinct() 
           .Select((p, i) => new { Key = p, Value = i + 1 }); 

或者在你的代碼:

var elementsWithIndex = elements.SelectMany(p => p.Properties.Keys) 
           .Distinct() 
           .Select((p, i) => new { Key = p, Value = i + 1 }); 
1

您可以簡單地使用它。

List<string> keys = new List<string>(); 
    keys.Add("a"); 
    keys.Add("b"); 
    keys.Add("c"); 
    keys.Add("d"); 
    keys.Add("e"); 
    keys.Add("f"); 
    keys.Add("g"); 


var fields = keys.Distinct().Select ((t,val)=> new { Key= t, Value= (val + 1)}); 
相關問題