Reputation: 369
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
Reputation: 32428
I think you want a list of Hal
s 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
Reputation: 120380
data.Join(
zipList,
hal => hal.zip,
zlKvp => zlKvp.Key,
(hal, zlKvp) => new {hal,zlKvp} //hal and KeyValuePair from zipList
);
Upvotes: 0
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 valuesHashSet<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 sideWhere
clause just filters the list of Hal
objects to those with a required zip
Upvotes: 4