从列表值创建对 [英] Create pairs from List values

查看:32
本文介绍了从列表值创建对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些值的列表,可以说1 2 3 4 5 6

I have a list with some values, lets say 1 2 3 4 5 6

我需要像这样将它们配对: 12 13 14 15 16 23 24 25 26 34 35 36 45 46 56

I need to pair them up like this: 12 13 14 15 16 23 24 25 26 34 35 36 45 46 56

基本上,我需要将它们混合在一起以创建唯一的值集.

Basically, I need to mix them all up to create unique sets of values.

您对如何创建这样的新列表有任何想法吗?

Do you have any ideas on how to create a new list like this?

谢谢您的输入!

推荐答案

对于示例数据,您可以使用一对简单的嵌套循环来实现:

For the data from your sample you can do it with a trivial pair of nested loops:

var list = new List<int>{1,2,3,4,5,6};
var res = new List<int>();
for (int i = 0 ; i != list.Count ; i++) {
    for (int j = i+1 ; j != list.Count ; j++) {
        res.Add(list[i]*10+list[j]);
    }
}

对于更复杂的数据,可以使用字符串连接技巧:

For more complex data, you can use a string concatenation trick:

var list = new List<int>{98,76,54,32,10};
var res = new List<int>();
for (int i = 0 ; i != list.Count ; i++) {
    for (int j = i+1 ; j != list.Count ; j++) {
        res.Add(int.Parse(string.Format("{0}{1}", list[i], list[j])));
    }
}

这篇关于从列表值创建对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆