Bohn
Bohn

Reputation: 26919

Create all combinations of two sets

I have two lists of strings, they are actually values of primary keys in database:

        List<string> hisSpecialtyKeysInDB = this.Repository.GetSpecialtyKeysOfThisProvider(providerKey);
        List<string> hisAddressKeysInDB = this.Repository.GetAddressKeysOfThisProvider(providerKey);

Either of them may or may not even have a value in it.

I want a combination of all possible combinations of these primary keys that these two lists might have. ( so for example if one has 3 items, the other has two items, I want to see six items)

I wrote this query below but its count is zero which is wrong. In my test one of these had zero items in it and the other had three, so I want three items to return. Can put the empty ones as string.Empty, that is fine by me.

        var temp = from ps in hisAddressKeysInDB
                   from pa in hisSpecialtyKeysInDB
        select new
        {
            PS = ps,
            PA = pa
        };

        int xxxxx = temp.Count();

Upvotes: 0

Views: 81

Answers (1)

Fede
Fede

Reputation: 4016

You can achieve what you need with the DefaultIfEmpty extension method. e.g.

var temp = from ps in hisAddressKeysInDB.DefaultIfEmpty("")
           from pa in hisSpecialtyKeysInDB.DefaultIfEmpty("")
           where ps != "" || pa != "" // This is to remove the edge case when both are empty
           select new
           {
               PS = ps,
               PA = pa
           };

Upvotes: 1

Related Questions