mch_dk
mch_dk

Reputation: 369

Linq join problem

Have the following:

class Hal
{
    public int zip { get; set; }
    public string Phone { get; set; }
    ...
}

List<Hal> data;
Dictionary<int, List<int>> zipList;

zipList - key is "zip" - value is a collection of related "zip"

Want to select all "Hal" objects with "zip" from ziplist "key" AND all related "zip" from ziplist "value".

How on earth do I do this in c# linq?

Upvotes: 0

Views: 300

Answers (3)

George Duckett
George Duckett

Reputation: 32428

I think you want a list of Hals with a zip contained in the dictionary, with the related Hal's as defined by the list of zips in the dictionary value.

var RelatedZips = from KeyValue in zipList
                  join halData in data on KeyValue.Key equals halData.zip
                  select new
                  {
                      ZipData = halData,
                      RelatedZipData = KeyValue.Value.Select(RelatedZipIndex =>
                          data.SingleOrDefault(d => d.zip == RelatedZipIndex))
                                    .Where(z => z != null)
                  };

Note: Code not typed in an IDE, and untested!

Upvotes: 1

spender
spender

Reputation: 120380

data.Join(
    zipList,
    hal => hal.zip,
    zlKvp => zlKvp.Key,
    (hal, zlKvp) => new {hal,zlKvp} //hal and KeyValuePair from zipList
);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499790

So you mean every Hal in data where the zip is either in the key or the value of zipList? I'd probably use:

var zips = new HashSet<int>(zipList.Keys
                                   .Concat(zipList.Values.SelectMany(x => x));
var hals = data.Where(x => zips.Contains(x.zip));

To explain:

  • zipList.Values.SelectMany(x => x) will just create a flattened view of all the values
  • That's concatenated with the keys within the dictionary
  • I'm creating a HashSet<int> from that for simplicity and efficiency of checking in the Where clause in a moment; alternatively a join would do this for us, but it feels simpler not to join when we're really only interested in one side
  • The Where clause just filters the list of Hal objects to those with a required zip

Upvotes: 4

Related Questions