How to remove an element from an IGrouping

2020-08-17 07:46发布

问题:

How do I remove an object directly from an IGrouping IGrouping<DateTime, VMAppointment>?

The only way I know of currently is to generate a new IGrouping without the concering element, but I don't like this way because it causes some trouble within my application.

Any ideas?

回答1:

No, there's no way to mutate an IGrouping<,>, at least in general - and even if you knew the concrete type, I don't believe any of the implementations exposed by the .NET framework allow the group to be mutated.

Presumably the grouping is the result of some query - so if possible, change the original query to exclude the values you aren't interested in.



回答2:

I know this is old question, but hopefully this helps someone else. A workaround for this is to cast the group to a list, then use the values from the list instead of the group.

var groups = someList.GroupBy(x => x...);

foreach (var group in groups)
{
    var groupList = group.ToList();

   ...

    groupList.Remove(someItem);

    //Process the other code from groupList.
}


回答3:

You could cast using Select and use TakeWhile if you have a testable condition (such as null as in the example) on a property in your group:

var removedItemsList = group.Select(x => x.TakeWhile(t => t.someProperty != null));

This will return an IEnumerable<IEnumerable<YourGroup>>.