所以这就是我试图做的事情:
symbolList: 1,1,1,2,2,2
valueList: a1,b1,c1,a2,b2,c2
result: 1|a1|b1|c1,2|a2|b2|c2
每个符号的a,b,c都是不同的值 对于每个符号,将存在相同数量的对应值。所以对于符号1,有三个值我想加入它。对于符号2,我希望第二组三个值连接到它,等等。 但是,根据我目前的实施情况,我目前得到:
result: 1|a1|b1|c1|a2|b2|c2, 2|a1|b1|c1|a2|b2|c2
这是我目前的代码:
List<string> results = symbolList.Distinct().Select(f =>
String.Join("|", new List<string>() { f }.Concat(valueList))).ToList();
string value = string.Join(",", results);
我试图以某种方式使用群组,但是没有找到可行的结果。非常感谢任何帮助。
答案 0 :(得分:3)
根据您的描述,配对索引看起来很重要,您不会尝试进行盲交错。以下是如何使用GroupBy执行此操作,我还在中间放置了一个3来演示订购。
List<string> symbolList = new List<string>() { "1", "1", "3", "2", "2", "2" };
List<string> valueList = new List<string>() { "a1", "b1", "c3", "a2", "b2", "c2" };
var items = symbolList.Zip(valueList, (symbol, value) => new {symbol, value}) //pairs the like indexes with each other in to an anonymous type.
.GroupBy(pair => pair.symbol, pair => pair.value) //Group together the values that share the same symbol
.OrderBy(group => group.Key) //optional, only if you want the output to be 1,2,3
.Select(group => String.Join("|", (new[] {group.Key}).Concat(group))); //Build up the "|" separated groups.
var result = String.Join(",", items); //Join together the groupings separated by ","
Console.WriteLine("result: " + result);
它给出结果result: 1|a1|b1,2|a2|b2|c2,3|c3
答案 1 :(得分:0)
请你试试这个:
List<string> symbolList = new List<string>() { "1", "1", "1", "2", "2", "2" };
List<string> valueList = new List<string>() { "a", "b", "c", "a", "b", "c" };
string value = string.Join(",", symbolList.Distinct().
Select(f => String.Join("|", new List<string>() { f }
.Concat(valueList.Distinct()))).ToList());
Console.WriteLine("result: " + value);
此代码为我提供result: "1|a|b|c,2|a|b|c"
。
我希望这就是你想要的。
答案 2 :(得分:0)
虽然不是原始问题的答案,但要严格回答标题(这是我来这里寻找的内容,只需将两个列表交错即可):
upwork , fivver , freelancer
示例:
var interleaved = list1.Zip(list2, (a, b) => new[] { a, b }).SelectMany(p => p);