c# 获取多个集合的组合结果

我的命题是多个int的list,每个集合任取一个,求组合。

最终代码为:

List<int> a = new List<int>() { 1, 2, 3 };
List<int> b = new List<int>() { 1, 2, 6 };
List<int> c = new List<int>() { 7, 8, 9 };
var d = a.Join(b, x => 1, x => 1, (x, y) => new List<int> { x, y });
var e = d.Join(c, x => 1, x => 1, (x, y) => 
{
    var tem = x.ToList();
    tem.Add(y);
    return tem;
});

这里主要用到的是集合的join方法。

join后面的参数的意思是,第一个参数,join的对象集合。第二个参数是一个函数,需要告诉程序第一个集合的每个元素提取连接键的函数。第三个参数也是函数,同第二个的作用,不过对象是第二个集合。我这里的处理是两个函数返回相同的键,任何值都可以,只要相同就行了。也就是完全连接。最后一个参数是连接成功之后,join函数返回什么对象。这里返回的是两者相加的集合。

在求e的过程中,前面三个参数的填充原因和求d函数的参数是一致的。需要注意的是第四个参数。因为List是一个对象,为了避免出现一些以外情况,我第一步将list复制到tem中,然后在tem的基础上添加后来加入的y,并返回tem。

最后得到的结果d.Count=9。为a,b的组合结果;e.Count=27,里面的每个元素都是长度为3的int集合。正是我想要的结果。

在这里,大家可以试试这段代码

List<int> a = new List<int>() { 1, 2, 3 };
List<int> b = new List<int>() { 1, 2, 6 };
List<int> c = new List<int>() { 7, 8, 9 };
var d = a.Join(b, x => 1, x => 1, (x, y) => new List<int> { x, y });
var e = d.Join(c, x => 1, x => 1, (x, y) => 
{
    x.Add(y);
    return x;//最终返回的e.Count=27,但是其中的每个元素都是长度为5的集合。第一个元素为{1,1,7,8,9}
    //var tem = x.ToList();
    //tem.Add(y);
    //return tem;
});

这段代码最后生成的e也是长度为27,但是其中的元素却是长度为5的集合。原因就在x的类型是List<int>。在直接对x执行Add时,引起x的不断叠加。注意:在这里,如果声明

var tem = x;

效果和上面是一样的,因为对tem也是List<int>,直接用x对其复制,会直接将x和tem的指针指向一个地方,修改tem和修改x的效果是一样的。这里必须用var tem = x.ToList();

 

12.11.22补充下段。继续调用join。同样是排列组合,但是有开关可以随时控制那些集合参与排列组合:

前台有三个checkBox的控件,分别对应下面的chkAA,chkBB,chkCC。

List<string> lstA = new List<string>() { "a", "b", "c" };
List<string> lstB = new List<string>() { "dd", "ee", "ff", "gg" };
List<string> lstC = new List<string>() { "hhh", "iii", "jjj", "kkk" };
var res = new List<List<string>>() { new List<string>() };
Func<List<string>, List<List<string>>> func = lst =>
{
    return res.Join(lst, x => 1, x => 1, (x, y) =>
        {
            var tem = x.ToList();
            tem.Add(y);
            return tem;
        }).ToList();
};
if (chkAA.Checked) res = func(lstA);
if (chkBB.Checked) res = func(lstB);
if (chkCC.Checked) res = func(lstC);

可以做到随时开关一个集合,使其不参与最终的排列组合。此代码是上面的扩展。

 

里面的术语可能不是很专业,如有疑问,可以留言;不足请更正。

posted @ 2012-09-13 09:34  脸谱匠  阅读(3692)  评论(0编辑  收藏  举报