我對 lambda 運算式并不完全清楚,我正在嘗試使用它們將以下字串轉換為字典,其中等號之前的專案是鍵,等號之后的專案是值。
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string stringOfKeyValuePairs = "Item1=value1 Item2=value2 Item3=value3 Item4=value4"
有沒有辦法拆分字串并使用 ToDictionary() 方法來獲得我想要的結果?
謝謝
編輯:我使字串更簡單,因為我已經可以將字串決議為我想要的,而復雜的版本對我正在尋找的資訊沒有任何價值。
uj5u.com熱心網友回復:
如果您熱衷于在 LINQ 中執行此操作,您可以執行幾個Splits 和 a ToDictionary,但感覺非常脆弱。我不知道是否永遠不會有空格,是否總是有唯一Key的 s,等等。如果這不是問題,像這樣:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string stringOfKeyValuePairs = "Item1=value1 Item2=value2 Item3=value3 Item4=value4";
var myDictionary = stringOfKeyValuePairs.Split(' ')
.Select(i => new KeyValuePair<string, string>(i.Split('=')[0],i.Split('=')[1]))
.ToDictionary(k => k.Key, k => k.Value);
myDictionary.ToList().ForEach(x => Console.WriteLine($"KEY: {x.Key} VALUE: {x.Value}"));
}
}
見: https ://dotnetfiddle.net/Uhekuv
輸出:
KEY: Item1 VALUE: value1
KEY: Item2 VALUE: value2
KEY: Item3 VALUE: value3
KEY: Item4 VALUE: value4
uj5u.com熱心網友回復:
您可以洗掉角括號并通過一些分隔符拆分字串(在您的情況下看起來它將是'=')。然后您可以使用回傳陣列的每個偶數索引元素作為鍵,奇數作為值并將其添加到字典中。此外,您應該在添加字典值之前洗掉任務。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410061.html
標籤:
上一篇:將資料框值映射到字典不起作用
