开发者

LINQ - GroupBy and project to a new type?

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

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 do I group by the Type, and project the grouped item into a new list of GroupedFilter, i.e:

public class Filter
{
    public int ItemID { get; set; }
    public string ItemName { get开发者_StackOverflow社区; set; }
}

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

Thanks.


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 GroupedFilter.Type property is a string to match your SearchFilter.Type property.


With Linq query syntax it is longer and more complex but just for reference:

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();

Somebody may find it more readable because they don't know all the possible parameters to GroupBy().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜