简体   繁体   English

C#转换列表 <string> 到字典 <string, string> LINQ

[英]C# Convert List<string> to Dictionary<string, string> LINQ

I have a JSON string[] like this : "['518','Incorrect date (it can not be earlier today or later today+1year)']" Which I deserialize using Json.Net library to a List, now I need to convert that list string to a Dictionary which key is the first value and the value is the second item in the list, following on. 我有一个像这样的JSON字符串[]:“ ['518','日期不正确(今天不能早于今天或今天晚1年)']“我使用Json.Net库反序列化到列表,现在我需要然后将该列表字符串转换为Dictionary,其键是列表中的第一个值,该值是列表中的第二个项。

I have done this using a for loop like this : 我已经使用了如下的for循环来做到这一点:

string Json = "['518','Incorrect CheckIn date (it can not be earlier today or later today+1year)']";
        var json = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(Json);

        var errorList = new ErrorList();
        for(int i=1;i<= json.Length;i++)
        {
            errorList.ErrorMessages.Add(new ErrorMessage(){ErrorCode = json[i -1], Message = json[i]});
            i = i + 1;
        }

I was wondering is there is a way to replace the fro loop with linq. 我想知道是否有一种方法可以用linq替换fro循环。

Thanks. 谢谢。

One of the Select extensions will give you the index of the item in the enumeration. Select扩展名之一将为您提供该项目在枚举中的索引。 With a bit of manipulation you can group the strings together into pairs like so: 通过一些操作,您可以将字符串分成几对,如下所示:

var pairs = 
    from item in json.Select((s, i) => new { index = i, value = s })
    // group by index / 2 to get pairs of values
    group item.value by item.index / 2 into grp
    // create ErrorMessage instances from the value pairs
    select new ErrorMessage { ErrorCode = grp.First(), Message = grp.Last() };

Or if you prefer fluent syntax: 或者,如果您更喜欢流利的语法:

var pairs = 
    json.Select((s,i) => new { s, i })
    .GroupBy(e => e.i / 2, e => e.s)
    .Select(g => new ErrorMessage{ ErrorCode = g.First(), Message = g.Last() });

Assuming your ErrorList type is derived from List<ErrorMessage> and has the AddRange method: 假设您的ErrorList类型是从List<ErrorMessage>派生的,并且具有AddRange方法:

errorList.AddRange(pairs);

Or you could just do pairs.ToList() to get the results as List<ErrorMessage> . 或者,您可以只做pairs.ToList()以将结果作为List<ErrorMessage>

You can try this way : 您可以这样尝试:

string Json = "['1','value1','2','value2','3','value3']";
var json = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(Json);

var result = json.Select((v, i) => new {value = v, index = i})
                 .Where(o => o.index%2 == 0)
                 .ToDictionary(o => o.value, o => json[o.index + 1]);

foreach (var pair in result)
{
    Console.WriteLine("key: {0}, value: {1}", pair.Key, pair.Value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM