Reputation: 630
So. I've got a list Property that groups values with identical names;
List<IGrouping<string, MyItemDTO>> MyList { get; set; }
It's initially populated from a database by means of an IQueryable<>
.
But say I wanted to add a new item to this list using code, how would I go about that? Since IGrouping is an interface, I can't exactly new it up like;
IGrouping<string, MyItemDTO> newGroup = new IGrouping<string, MyItemDTO>();
MyList.Add(newGroup);
That doesn't work. I'd like to know, 'what does?' How do I get a new item in there?
Many thanks.
EDIT:
A little perspective:
Imagine having two or more cities. These cities have a few respective streets with matching names. IGrouping<,>
ensures that the street name appears only once in the List. Therefore the data-bound Combobox
doesn't repeat any values (typically because the end user won't know to what city the street belongs to).
My view has two Combobox
es. One for street, the other for city. Should a street be selected, the viewmodel will select the corresponding city, unless the street group contains more that one street within it. At that point, the user will be prompted to manually select which city the street resides in.
I figured that IGrouping<,>
would suit this purpose seeing as it's the default return type when using the GroupBy() extension method. Still open to suggestions though.
Upvotes: 1
Views: 6905
Reputation: 2803
I think You really do not needed IGrouping
in your Property , What rather you need is a collection like Dictionary
, List
etc.
Still if you want it then here's how you should add items with IGrouping
var t = new List<Test>();
foreach (var item in t.GroupBy(x => x.A))
{
A.MyList.Add(item);
}
public static class A
{
public static List<IGrouping<string, Test>> MyList { get; set; }
}
public class Test
{
public string A { get; set; }
public int B { get; set; }
}
Hope that helps !!
Upvotes: 0
Reputation: 773
Use this method to create IGrouping value:
IGrouping<string, MyItemDTO> GetIGrouping(string key,MyItemDTO item)
{
return new[] {item}.GroupBy(val => key).First();
}
or if you want several items in group:
IGrouping<string, MyItemDTO> GetIGrouping(string key,IEnumerable<MyItemDTO> items)
{
return items.GroupBy(val => key).First();
}
Upvotes: 3
Reputation: 113382
Either use a GroupBy
call on an IEnumerable<T>
that produces what you want, or implement IGrouping<TKey, TElement>
as per this answer to a question about that particular approach.
Upvotes: 0