简体   繁体   English

C#:将数据添加到字典

[英]C#: Adding data to dictionary

I have a list like 我有一个类似的清单

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

I need to add data to the dictionary from the above list 我需要将数据从以上列表添加到字典中

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

so the Dict should contain 所以Dict应该包含

Key --> 66 value --> 67

i need to take 66(first value) from first string([66,X,X]) and 67(first value) from second string( [67,X,X]) and add it as a key value pair into the dictionary. 我需要从第一个字符串([66,X,X])中获取66(第一个值),从第二个字符串([67,X,X])中获取67(第一个值),并将其作为键值对添加到字典中。

Now i'm following string replacing and looping methodology to do this . 现在,我正在按照字符串替换和循环方法进行此操作。

Is there any way to do this in LINQ or Regular expression. 有什么办法可以在LINQ或正则表达式中执行此操作。

After your comment that you're starting from a list of lists, I understood what you were after. 在您从列表列表开始发表评论之后,我了解了您的要求。 I'm reusing Jaroslav's 'GetNumber' function here. 我在这里重用Jaroslav的“ GetNumber”功能。 Wrote my sample with array of array of string, but should work just the same. 用字符串数组array编写了我的示例,但是应该可以正常工作。 The code below will throw if you have duplicate keys, which I presume is what you want if you're using a dictionary. 如果您有重复的键,则下面的代码将抛出,如果使用字典,我想这就是您想要的。

        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);

Here is an example using both string.Split() and a Regex: 这是同时使用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>();
    }
}

i suspect that your example is quite contrived though, so there may be a better solution especially if you need to process large numbers of strings into key/value pairs (i deliberately hardcoded index values because your example was quite simple and i didn't want to over complicate the answer). 我怀疑您的示例非常人为,因此可能会有更好的解决方案,尤其是当您需要将大量字符串处理为键/值对时(我故意对索引值进行硬编码,因为您的示例非常简单并且我不想使答案过于复杂)。 If the input data is consistent in format then you can make assumptions like using fixed indexes, but if there is a possibility of some variance then there may need to be more code to check the validity of it. 如果输入数据在格式上是一致的,则可以进行假设,例如使用固定索引,但是如果有可能出现差异,则可能需要更多代码来检查其有效性。

You can use a regular expression to extract the value from each item in the list, and if you want, use LINQ to select out two lists and zip them together (in C# 4.0): 您可以使用正则表达式从列表中的每个项目中提取值,如果需要,可以使用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);

If you're using C# 3.5, you can use Eric Lippert's implementation of Zip() . 如果使用的是C#3.5,则可以使用Eric Lippert的Zip()实现

IF I understand correctly: you want to create linked nodes like 66 -> 67, 67 -> 68, ... n -> n+1 ? 如果我理解正确:您想创建链接节点,例如66 -> 67, 67 -> 68, ... n -> n+1吗?

I would not use LINQ: 我不会使用LINQ:

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

And in code: 并在代码中:

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

    Dict.Add(first, second);
}

You should also perform checking, etc. 您还应该执行检查等。
The sample assumes a list with at least 2 items. 该示例假定一个列表至少包含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