How to remove an element from an IGrouping

蓝咒 提交于 2019-12-10 02:48:53

问题


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>>.



来源:https://stackoverflow.com/questions/12163855/how-to-remove-an-element-from-an-igrouping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!