tags:

views:

49

answers:

2
+1  Q: 

Getting sub list

From the given set

{1,2,3,4,5,6,7,8,99,89}

What is the way to get all possible two numbers subset using LINQ?

(i.e) {1,2},{1,3},{1,4} .....

+6  A: 

cross join?

var data = new[] {1,2,3,4,5,6,7,8,99,89};
var qry = from x in data
          from y in data
          where x < y
          select new {x,y};
foreach (var pair in qry) {
    Console.WriteLine("{0} {1}", pair.x, pair.y);
}


For triples:

var data = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 99, 89 };
var qry = from x in data
          from y in data
          where x < y
          from z in data
          where y < z
          select new { x, y, z };
foreach (var tuple in qry) {
    Console.WriteLine("{0} {1} {2}", tuple.x, tuple.y, tuple.z);
}
Marc Gravell
+1, holy sh*t, Batman!
Rubens Farias
Suppose when i go for three number set {1,2,3} {1,3,4} shall i usevar qry = from x in data from y in data from z in data where x> y and x>z and y >z select new {x,y,z} ?
RusselUdana
Marc Gravell
or you could call .Distinct()
caiokf
If so please update it in your answer Mr Marc Gravell. Thanks a ton.
RusselUdana
@caiokf: my point relates to whether {1,2} is different to {2,1} - but the OP mentioned "subset", and a "set" is not ordered - thus as true subsets, {1,2} and {2,1} are identical. For info, `Distinct()` **wouldn't** work for this.
Marc Gravell
@RusselUdana - I ended up doing something slightly between the two... it should still perform, without making the query more complex...
Marc Gravell
+1  A: 

This link doesn't support LINQ queries, but I consider it related and relevant: Permutations, Combinations, and Variations using C# Generics

Rubens Farias