首页 新闻 会员 周边

怎么使用LINQ实现对List<List<string>>循环并拼接字符串

0
[已解决问题] 解决于 2014-09-26 22:16

List<List<string>> proplist = new List<List<string>>();

List<string> l0 = proplist[0];

List<string> l1 = proplist[1];
List<string> l2 = proplist[2];

var list = from s1 in l0
              from s2 in l1
              from s3 in l2
              select s1 + s2 + s3;

我现在是这么写的,但是有个问题,就是proplist不是固定3个,有的时候只有2个,所以会报错

墙头草的主页 墙头草 | 初学一级 | 园豆:6
提问于:2014-07-20 21:27
< >
分享
最佳答案
0

以下代码测试通过:

List<List<string>> proplist = new List<List<string>>();
proplist.Add(new List<string>(){"a","b"});
proplist.Add(new List<string>() { "c", "d" });
Console.WriteLine(string.Join("", proplist.Select(x => string.Join("", x))));
奖励园豆:5
dudu | 高人七级 |园豆:30994 | 2014-07-20 21:48

你这个不对啊,我的意思是这样的

List<List<string>> proplist = new List<List<string>>();
proplist.Add(new List<string>(){"a","b"});
proplist.Add(new List<string>() { "c", "d" });

然后循环结果是

ac

ad

bc

bd

这样

墙头草 | 园豆:6 (初学一级) | 2014-07-20 21:53

@墙头草: 

这个操作在英文中叫pairwise,提供一个思路:将List<List<string>>转换成List<string>,也就是new List<string>(){"a","b", "c", "d"},然后使用MoreLINQ的Pairwise()方法。

dudu | 园豆:30994 (高人七级) | 2014-07-20 22:30

@dudu: 这个...如果我有{"a","b","c"} {"b", "c", "d" }

 

也能做到吗,有没有详细的例子啊

墙头草 | 园豆:6 (初学一级) | 2014-07-20 23:50
其他回答(2)
0

mark一下。。。

羽商宫 | 园豆:2490 (老鸟四级) | 2014-07-21 17:11
0

List<List<string>> proplist = new List<List<string>>();
proplist.Add(new List<string>(){"a","b"});
proplist.Add(new List<string>() { "c", "d" });

var pinyinList = proplist .Aggregate((cur, next) => {

List<string> val = new List<string>();
foreach (var item in cur)
{
foreach (var item2 in next)
{
val.Add(item + item2);
}
}

foreach (var item in pinyinList)
{
 Debug.Log(item);
}

小虾吃大虾 | 园豆:202 (菜鸟二级) | 2016-04-21 13:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册