![](/img/trans.png)
[英]using linq and c# to create a nested list object from a flat list object
[英]Create a nested list from a flat list using Linq
我有一个类似的字符串列表
A01,B01 ,A02, B12, C15, A12, ...
我想将列表展开为列表列表或列表字典,以便
所有以相同字母开头的字符串都组合在一起(使用linq)
A -> A01 , A02 , Al2
B -> B01 , B12
C -> C15
要么
A -> 01 , 02 , l2
B -> 01 , 12
C -> 15
现在,我只是使用for循环迭代列表,并将值从字典添加到approp列表。
(可能不正确!)
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
foreach( string str in stringList)
{
string key = str.Substring(0,1);
if (!dict.ContainsKey(key)){
dict[key] = new List<string>();
}
dict[key].Add(str);
}
编辑 :
哦,对不起,我忘了添加它,我有一个Category objs列表,这些是Category名称。
我需要检索诸如Dictionary<string, List<Category>>
,然后将其绑定到嵌套列表 。 (asp.net/ mvc)
有没有更好的方法可以使用Linq进行相同的操作?
来自聊天室,请尝试此操作。 我知道这不是最优雅的解决方案,可能会有更好的解决方案。
List<string> listOfStrings = {"A01", "B01", "A02", "B12", "C15", "A12"}.ToList();
var res = listOfStrings.Select(p => p.Substring(0, 1)).Distinct().ToList().Select(p =>
new {
Key = p,
Values = listOfStrings.Where(c => c.Substring(0, 1) == p)
}).ToList();
foreach (object el_loopVariable in res) {
el = el_loopVariable;
foreach (object x_loopVariable in el.Values) {
x = x_loopVariable;
Console.WriteLine("Key: " + el.Key + " ; Value: " + x);
}
}
Console.Read();
提供以下输出:
如果您想使用字典,则可能需要
List<String> strList = new List<String>();
strList.Add("Axxxx");
strList.Add("Byyyy");
strList.Add("Czzzz");
Dictionary<String, String> dicList = strList.ToDictionary(x => x.Substring(0, 1));
Console.WriteLine(dicList["A"]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.