LINQ - GroupBy and a new type of project?

I have a list of items i.e. List<SearchFilter>, and this is an object SearchFilter:

public class SearchFilter
{
    public int ItemID { get { return ValueInt("ItemID"); } }
    public string ItemName { get { return ValueString("ItemName"); } }
    public string Type { get { return ValueString("Type"); } }
}

How can I group by Typeand design a grouped item into a new list GroupedFilter, i.e.:

public class Filter
{
    public int ItemID { get; set; }
    public string ItemName { get; set; }
}

public class GroupedFilter
{
    public int Type { get; set; }
    public List<Filter> Filters { get; set; }
}

Thank.

+3
source share
2 answers
var result = items.GroupBy(
    sf => sf.Type,
    sf => new Filter() { ItemID = sf.ItemID, ItemName = sf.ItemName },
    (t, f) => new GroupedFilter() { Type = t, Filters = new List<Filter>(f) });

But you need to make sure your property GroupedFilter.Typeis stringin order to match your property SearchFilter.Type.

+5
source

With the Linq query syntax, it is longer and more complex, but for reference only:

var grpFilters = (from itm in list group itm by itm.Type into grp select
                    new GroupedFilter
                    {
                        Type = grp.Key,
                        Filters = grp.Select(g => new Filter 
                                                  {
                                                      ItemID = g.ItemID,
                                                      ItemName = g.ItemName
                                                  }).ToList()
                    }).ToList();

Someone may find it more readable because they do not know all the possible parameters for GroupBy ().

0
source

All Articles