c# - Get all combinations of items in an array -


i have text files in folder such f1.txt,f2.txt,....f15.txt. want combination of them has length 2.

the final result should

{f1.txt, f2.txt}, {f1.txt, f3.txt}....

i used code

 static ienumerable<ienumerable<t>>  getkcombs<t>(ienumerable<t> list, int length) t : icomparable  {         if (length == 1) return list.select(t => new t[] { t });         return getkcombs(list, length - 1)             .selectmany(t => list.where(o => o.compareto(t.last()) > 0),                 (t1, t2) => t1.concat(new t[] { t2 }));  } 

then call main method.

string[] files = directory.getfiles(@"c:\users\downloads\samples", "*.txt"); ienumerable<ienumerable<string>> filescombination = getkcombs(files, 2); 

but why got nothing?

edit:

        foreach(var x in filescombination)         {             console.writeline(x);         } 

in immediate window, have

?x           {system.linq.enumerable.concatiterator<string>}             first: null             second: null 

check 'files' contains list of files expect.

the method working expected. tested in small test app:

class program {     static void main(string[] args)     {         list<int> list = new list<int> { 1, 2, 3, 4 };          ienumerable<ienumerable<int>> result = getkcombs(list, 2);          foreach (var line in result)         {             foreach (var item in line)             {                 console.write("{0}, ", item);             }             console.writeline();         }          console.readkey();     }      static ienumerable<ienumerable<t>> getkcombs<t>(ienumerable<t> list, int length) t : icomparable     {         if (length == 1) return list.select(t => new t[] { t });         return getkcombs(list, length - 1)             .selectmany(t => list.where(o => o.compareto(t.last()) > 0),                 (t1, t2) => t1.concat(new t[] { t2 }));     } } 

edit:

in code have:

    foreach(ienumerable<string> x in filescombination)     {         console.writeline(x);     } 

when console.writeline(x) it's equivalent console.writeline(x.tostring()). default behaviour of tostring() show name of object.

the reason why in debug mode first: null , second: null because of deferred execution. ienumerable object doesn't yet know value is, until try use values, tolist() or iterator, example.


Comments

Popular posts from this blog

Change the color of an oval at click in Java AWT -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -