简体   繁体   中英

How to group LINQ query to dictionary<string, string>

I have a simple model that I'm trying to group:

public class PracticeArea
{
    [Key]
    public int PracticeAreaID { get; set; }

    public string Name { get; set; }

    public string Type { get; set; }

}

I'd like to group by Type, how can I convert this:

var practiceAreas = (from c in db.PracticeAreas
                             select c).

to:

public Dictionary<string, string> groupedPracticeAreas { get; set; }

I'm not sure how grouping works within Linq - I can run .ToGroup(),. but that doesn't give me my dictionary.

I've tried:

practiceAreas = practiceAreas.ToDictionary(x => x.Type, x => x.Name);

But that gave me a cast error

This should not throw cast exception if both type and name are strings:

practiceAreas.ToDictionary(x => x.Type, x => x.Name)

But this would throw if there is more than one practice area exist for some type. You can use one of following options:

1) Use lookup instead of dictionary. It will create lookup for names by area type

practiceAreas.ToLookup(pa => pa.Type, pa => pa.Name)

2) Use dictionary with collection to hold all names for each type, eg Dictionary<string, List<string>> :

practiceAreas.GroupBy(pa => pa.Type)
             .ToDictionary(g => g.Key, g => g.Select(pa => pa.Name).ToList())

3) Join all names in single string

practiceAreas.GroupBy(pa => pa.Type)
         .ToDictionary(g => g.Key, g => String.Join("," g.Select(pa => pa.Name)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM