TheAkhemist
TheAkhemist

Reputation: 219

Create Dictionary and use key in value expression declaration

I have two lists and would like to create a dictionary of key value pair type Key = string of each unique reference (of type string) Value = sub list of list2 where list2 uniquereference are equal to Key (the value is of type List)

I want to do it in essense like this

var dictionary = listA.ToDictionary(x => x.StringProperty, y => List2.Where(x => x.Reference == x.StringProperty)

How can I do this in a expression declaration? As I currently have a method to create this dictionary?

I had to create this method to generate what I wanted. Is there an expression that will do the same thing:

   private Dictionary<string, IEnumerable<JobEntity>> Dictionary(IEnumerable<JobLinkedBag> jobLinkedBags, IEnumerable<JobEntity> jobs)
    {
        if (jobLinkedBags == null || jobs == null || jobLinkedBags.Count() == 0 || jobs.Count() == 0)
            return null;

        var dictionary = new Dictionary<string, IEnumerable<JobEntity>>();

        for (int i = 0; i < jobLinkedBags.Count(); i++)
        {
            var thisBag = jobLinkedBags.ElementAt(i).LuggageCode;
            var jobsForThisBag = jobs.Where(x => x.LuggageCode == thisBag);
            dictionary.Add(thisBag, jobsForThisBag);
        }
        return dictionary;
    }

Upvotes: 1

Views: 471

Answers (1)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43906

The 1:1 translation of your method into an expression would look like this:

Expression<Func<IEnumerable<JobLinkedBag>, IEnumerable<JobEntity>, Dictionary<string, IEnumerable<JobEntity>>>> expression =
        (jobLinkedBags, jobs) => (jobLinkedBags == null || jobs == null || jobLinkedBags.Count() == 0 || jobs.Count() == 0)
                ? null
                : jobLinkedBags.ToDictionary(
                             jlb => jlb.LuggageCode,
                             jlb => jobs.Where(job => job.LuggageCode == jlb.LuggageCode));

Note that there are some dangerous parts in this code:

  • this codes enumerates the arguments jobLinkedBags and jobs several times (to determine the count and then to filter them), this may cause problems depending on what specific IEnumerable implementation they are
  • you build a dictionary that has IEnumerable as value. This enumeration is also executed defered. So you should make sure that the sources of this enumeration are still valid when you eventually will iterate through it.

Upvotes: 1

Related Questions