簡體   English   中英

C#:將數據添加到字典

[英]C#: Adding data to dictionary

我有一個類似的清單

List<string> TempList = new List<string> { "[66,X,X]", "[67,X,2]", "[x,x,x]" };

我需要將數據從以上列表添加到字典中

Dictionary<int, int> Dict = new Dictionary<int, int>();

所以Dict應該包含

Key --> 66 value --> 67

我需要從第一個字符串([66,X,X])中獲取66(第一個值),從第二個字符串([67,X,X])中獲取67(第一個值),並將其作為鍵值對添加到字典中。

現在,我正在按照字符串替換和循環方法進行此操作。

有什么辦法可以在LINQ或正則表達式中執行此操作。

在您從列表列表開始發表評論之后,我了解了您的要求。 我在這里重用Jaroslav的“ GetNumber”功能。 用字符串數組array編寫了我的示例,但是應該可以正常工作。 如果您有重復的鍵,則下面的代碼將拋出,如果使用字典,我想這就是您想要的。

        var input = new []
                        {
                            new [] { "[66,X,X]", "[67,X,2]", "[x,x,x]" },
                            new [] { "[5,X,X]", "[8,X,2]", "[x,x,x]" }
                        };

        var query = from l in input
                    select new 
                    {
                     Key = GetNumber(l.ElementAt(0)), 
                     Value = GetNumber(l.ElementAt(1))
                     };

        var dictionary = query.ToDictionary(x => x.Key, x => x.Value);

這是同時使用string.Split()和Regex的示例:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> data = new List<string>() { "[66,X,X]", "[67,X,2]", "[x,x,x]" };
            addToDict(data);

            Console.ReadKey();
        }

        private static void addToDict(List<string> items)
        {
            string key = items[0].Split('[', ',')[1];
            string val = items[1].Split('[', ',')[1];

            string pattern = @"(?:^\[)(\d+)";
            Match m = Regex.Match(items[0], pattern);
            key = m.Groups[1].Value;
            m = Regex.Match(items[1], pattern);
            val = m.Groups[1].Value;

            _dict.Add(key, val);
        }

        static Dictionary<string, string> _dict = new Dictionary<string, string>();
    }
}

我懷疑您的示例非常人為,因此可能會有更好的解決方案,尤其是當您需要將大量字符串處理為鍵/值對時(我故意對索引值進行硬編碼,因為您的示例非常簡單並且我不想使答案過於復雜)。 如果輸入數據在格式上是一致的,則可以進行假設,例如使用固定索引,但是如果有可能出現差異,則可能需要更多代碼來檢查其有效性。

您可以使用正則表達式從列表中的每個項目中提取值,如果需要,可以使用LINQ選擇兩個列表並將它們壓縮在一起(在C#4.0中):

var regex      = new Regex(@"\d+");
var allValues  = TempList.Select(x =>int.Parse(regex.Match(x).Value));
var dictKeys   = allValues.Where((x,index)=> index % 2 == 0); //even-numbered 
var dictValues = allValues.Where((x,index)=> index % 2 > 0); //odd numbered 
var dict       = dictKeys.Zip(dictValues, (key,value) => new{key,value})
                         .ToDictionary(x=>x.key,x=>x.value);

如果使用的是C#3.5,則可以使用Eric Lippert的Zip()實現

如果我理解正確:您想創建鏈接節點,例如66 -> 67, 67 -> 68, ... n -> n+1嗎?

我不會使用LINQ:

private static int GetNumber(string s)
{
    int endPos = s.IndexOf(',');
    return Int32.Parse(s.Substring(1, endPos-1));
}

並在代碼中:

int first, second;    
for (int i = 1; i < TempList.Count; i++)
{
    first = GetNumber(TempList[i - 1]);
    second = GetNumber(TempList[i]);

    Dict.Add(first, second);
}

您還應該執行檢查等。
該示例假定一個列表至少包含2個項目。

List<List<string>> source = GetSource();

Dictionary<int, int> result = source.ToDictionary(
  tempList => GetNumber(tempList[0]),
  tempList => GetNumber(tempList[1])
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM