Get distinct combination of n elements with x variable combination of each in c#

Valentin Duhamel 1 Reputation point
2022-04-07T12:00:54.48+00:00

I have a dataset data representing items in a sql db:

190888-image.png

I can have several rows for an item as I can have several suppliers able to provide it to me.

I'm getting these data and convert it to a list of objects:

 public class ItemBySupplier  
    {  
        public string Item { get; set; }  
        public string Supplier { get; set; }  
    }  

So I have a list of this items in a variable :

List<ItemBySupplier> itemBySuppliers  

I would like to iterate over this list to get all distinct combinations possible.

Where each combination should contains a distinct list of ALL items.

I know that I will have 4 combinations possible as only two items can be found in two different suppliers:

I'm expecting to outputs the same a list of the same objects (ItemBySupplier).

The desired output would be:

  1. item1-supplierA / item2-supplierB / item3-supplierD / item4-supplierE
  2. item1-supplierA / item2-supplierC / item3-supplierD / item4-supplierE
  3. item1-supplierA / item2-supplierB / item3-supplierD / item4-supplierF
  4. item1-supplierA / item2-supplierC / item3-supplierD / item4-supplierF

Any help would be much appreciate.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,470 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Valentin Duhamel 1 Reputation point
    2022-04-07T13:10:14.68+00:00

    I finally found the solution:

    var items = itemBySuppliers.Select(d => d.Item).Distinct().OrderBy(t => t);
    var a = items.Select(t => itemBySuppliers.Where(d => d.Item == t));
    
    IEnumerable<IEnumerable<ItemBySupplier>> query = a.First().Select(e => new[] { e });
    
    foreach (var e in a.Skip(1))
    {
        query = query.Join(e, od => true, id => true, (ods, id) => ods.Concat(new[] { id }));
    }
    
    List<IEnumerable<ItemBySupplier>> combinations = query.ToList();
    
    0 comments No comments