简体   繁体   English

转换列表<string>包含多对多关系项为一对多关系</string>

[英]Convert List<string> containing many-to-many relationship items into one-to-many relationship

I have a List that contains strings which are delimited by a ' ' The list serves to function as a list of many to many relationships:我有一个包含由“”分隔的字符串的列表,该列表作为多对多关系的列表提供给 function:

Category1 Item1
Category1 Item2
Category1 Item3
Category2 Item1 
Category2 Item2 
Category2 Item3
Category2 Item4
Category2 Item5
Category3 Item1 

I need to convert this list into one which has a one to many relationship order, with the items separated by a ';'我需要将此列表转换为具有一对多关系顺序的列表,其中项目由“;”分隔example:例子:

Category1 Item1;Item2;Item3
Category2 Item1;Item2;Item3;Item4;Item5
Category3 Item1

I have multiple foreach loops right now.我现在有多个 foreach 循环。 I would love to share with you the many methods I've tried but it's truly a mess.我很乐意与您分享我尝试过的许多方法,但这确实是一团糟。 However, something tells me there might be a Lambda technique to achieve this.但是,有些事情告诉我可能有一种 Lambda 技术来实现这一点。 Can anyone point me in the right direction?谁能指出我正确的方向? Thanks谢谢

var items = new List<string> {
   "Category1 Item1",
   "Category1 Item2",
   "Category1 Item3",
   "Category2 Item1",
   "Category2 Item2",
   "Category2 Item3",
   "Category2 Item4",
   "Category2 Item5",
   "Category3 Item1"
};

var result = items.Select(x => x.Split(' '))
                  .Select(x => new {
                     Category = x[0],
                     Item = x[1]
                  })
                  .GroupBy(x => x.Category, y => y.Item, (k, e) => string.Join(";", e))
                  .ToList();

Console.ReadLine();

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

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