Diskuze: List to dictionary
Člen
Zobrazeno 6 zpráv z 6.
//= Settings::TRACKING_CODE_B ?> //= Settings::TRACKING_CODE ?>
Do toho tvaru si to dávaš ty? Nebolo by lepšie oddeliť nejako inak? Napríklad <Key>=<Value>/<Key>=<Value>/<Key>=<Value>
Potom by si napríklad mohol použiť LINQ.
var dict = text.Split(new[] {'//'}, StringSplitOptions.RemoveEmptyEntries)
.Select(part => part.Split('='))
.ToDictionary(split => split[0], split => split[1]);
S tím tvarem, který dostávám, bohužel nic neudělám.
Tak neviem, či ešte niečo iné nájdeš. Asi na to bude treba spraviť vlastnú metódku. Ale možno niekoho ešte niečo napadne.
Už to dělám vlastní metodou, ale tak chtěl jsem se zeptat, jestli na to už něco není..
Dictionary<string, string> info = new Dictionary<string, string>();
string key = "";
bool isValue = false;
foreach (string value in serverInfo.Split((char)0x5C).Skip(1))
{
if (isValue)
{
info[key] = value;
}
else
{
key = value;
}
isValue = !isValue;
}
return info;
public static class Extensions
{
public static Dictionary<string,string> ConvertToDictionary(this string s, char separator)
{
var dic = new Dictionary<string,string>();
var splitted = s.Split(separator);
if (splitted.Length % 2 != 0)
throw new Exception("Invalid input string");
for (int i = 0; i < splitted.Length; i += 2)
{
dic.Add(splitted[i], splitted[i + 1]);
}
return dic;
}
}
Jde to napsat i v LINQu, ale nvm jak efektivní to bude.
public static Dictionary<string, string> ConvertToDictionary2(this string s, char separator)
{
var splitted = s.Split(separator);
if (splitted.Length % 2 != 0)
throw new Exception("Invalid input string");
return splitted.Zip(splitted.Skip(1), (Key, Value) => new { Key, Value })
.Where((pair, index) => index % 2 == 0)
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
Zobrazeno 6 zpráv z 6.