1

I am storing a list of Choices of Enum values and my Enum looks like below

enum OrderDay 
{
    Sunday,
    Monday,
    Wednesday,
    Friday,
    Saturday
};
List<OrderDay> DayChoices;  //List stores the selected values

Initially the List contains 3 values

{
Wednesday,
Friday,
Saturday
}

How to filter out a specific value from this list and makes list as

{
    Wednesday,
    Friday
}

This is the code i was trying , but ended up as build error. Trying to recreate the list without the given day value

private async Task OnChipDayEnumClose(OrderDay val)
{ 
    DayChoices = DayChoices.Where(s => s != val).ToList();
}
Sebastian
  • 4,625
  • 17
  • 76
  • 145
  • 1
    You should also paste the "build error" – sachin Dec 21 '21 at 16:08
  • 4
    `List` has a `RemoveAll` method that takes in a predicate... you don't need linq – Zohar Peled Dec 21 '21 at 16:09
  • 2
    Meanwhile, `OnChipDayEnumClose` doesn't need to be async. It serves no purpose. – madreflection Dec 21 '21 at 16:10
  • What happened to Tuesday and Thursday :) Also if you don't know, there's already a [DayOfWeek](https://learn.microsoft.com/en-us/dotnet/api/system.dayofweek?view=net-6.0) enum. – Trevor Dec 21 '21 at 16:13
  • Do you have a List of the filtered options? Use the Except Method to get the filtered List – demoncrate Dec 21 '21 at 16:17
  • @zaggler I used Days as an enum easy to convey the problem i am facing . The real enum is a different one Thank you – Sebastian Dec 21 '21 at 16:18
  • 1
    @ZoharPeled Thank you managed to sort it using Remove method of List – Sebastian Dec 21 '21 at 16:19
  • 1
    @Sebastian I wouldn't have thought that considering your comment in your post, `my Enum looks like below`... thanks. – Trevor Dec 21 '21 at 16:19
  • 2
    Does this answer your question? [Filtering collections in C#](https://stackoverflow.com/questions/26196/filtering-collections-in-c-sharp) includes `linq`, `RemoveAll`, `yield` etc. solutions.... – Trevor Dec 21 '21 at 16:21
  • I might be being a bit thick, but why is this not just `Remove(Saturday)`? – Caius Jard Dec 21 '21 at 16:46
  • `OnChipDayEnumClose` is declared to return a `Task` but it does not in fact return a `Task`... – Dialecticus Dec 21 '21 at 16:59

1 Answers1

3

You have to re-assign filtered collection after filtering, try this, it was tested in VS and working properly


List<OrderDay> dayChoices = new List<OrderDay> { OrderDay.Wednesday, OrderDay.Friday, OrderDay.Saturday };

dayChoices = OnChipDayEnumClose(dayChoices, OrderDay.Wednesday);


private List<OrderDay> OnChipDayEnumClose(List<OrderDay> dayChoices, OrderDay val)
{
    return dayChoices.Where(s => s != val).ToList();
}

or an alternative variant, thanks to @zaggler

private void OnChipDayEnumClose(List<OrderDay> dayChoices, OrderDay val)
{
    dayChoices.RemoveAll(s => s == val);
}   
Serge
  • 40,935
  • 4
  • 18
  • 45