开发者

Generate all possible combinations of several columns in .NET

I have like 4 columns in a file, each column contains a number of values, more or less. I need to get all possible combinations, while order of columns and number of sections in resulting strings should rem开发者_C百科ain the same.

E.g. first column contains numbers ranging 1-100, second: letters a-z, and the third one is also numeric, I would get something like

1-A-1, 2-A-1, 3-A-1; 1-B-1, 1-B-2, 1-B-3 and so on.


There are various general-purpose approaches to this, but the simplest for a case where you know exactly how many columns you've got is just to use nested loops:

foreach (var a in firstColumn)
{
    foreach (var b in secondColumn)
    {
        foreach (var c in thirdColumn)
        {
           foreach (var d in fourthColumn)
           {
               // Do something with a, b, c, d
           }
        }
    }
}

Alternative using LINQ:

var query = from a in firstColumn
            from b in secondColumn
            from c in thirdColumn
            from d in fourthColumn
            select new { a, b, c, d };
foreach (var tuple in query)
{
    // Do something with tuple.a, tuple.b etc
}


Assuming you have parsed the file into a list of Foo objects where each property contains the value of a column:

class Foo
{
    public string Column1 { get; set; }
    public string Column2 { get; set; }
    public string Column3 { get; set; }
    public string Column4 { get; set; }
}

List<Foo> list = ParseFile();


var query = from f1 in list
            from f2 in list
            from f3 in list
            from f4 in list
            select new Foo
            {
                Column1 = f1.Column1,
                Column2 = f2.Column2,
                Column3 = f3.Column3,
                Column4 = f4.Column4,
            };

Foo[] combinations = query.ToArray();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜