0

I have a model that looks like this

     [Column("StatusId")]
     public FileStatus Status { get; set; }

     public int Id { get; set; }

I also have an enum that looks like this.

     public enum FileStatus
        {
            MessageInProgress,
            MessageDone,
            NoMessage
        }

I am pulling data from my repository to populate data variable below

    IEnumerable<MyFile> data = await _fileDataRepository.GetAllData(Id);

I want to filter data such that I will remove any record that has a status of MessageDone or NoMessage.

This code does not work for me.

    data.where( x => x.Status != "MessageDone" | x.Status != "NoMessage")

How do I achieve the filtering?

Baba
  • 2,059
  • 8
  • 48
  • 81
  • dont use strings. use `&&` instead of `|`. don't capture as an `IEnumerable` as it will pull things too much. – Daniel A. White Mar 04 '20 at 17:19
  • Instead of using a string why not just use the enum itself? `x.Status != FileStatus.MessageDone`. Also you should have `&&` instead of `|` for the comparison operator. – Jesse Mar 04 '20 at 17:20
  • I'd add an overload `GetAllData(Id, status)` where `status` is one of `FileStatus` values and do the filter in the DAL. –  Mar 04 '20 at 18:04

1 Answers1

2

2 things you need to change:

  1. FileStatus is enum and you use it as a string.
  2. You used | which is "boolean logical or" and you should use "Conditional logical and" && (You can use & but most of the times is better to use conditional operator because of the laziness (For more details)).

You should change it to:

data.where(x => x.Status != FileStatus.MessageDone && x.Status != FileStatus.NoMessage)

Or more simple:

data.where(x => x.Status == FileStatus.MessageInProgress)

itaiy
  • 1,152
  • 1
  • 13
  • 22
  • Good answer and explanation with solution; the last code snippet is best. – Trevor Mar 04 '20 at 17:28
  • The reason why I used Or | is that I want to filter the data when the enum is MessageDone, or NoMessage. Both of this message cannot exist at the same time. It is just one at a time that can exist in the table – Baba Mar 04 '20 at 17:29
  • from MSDN: The result of x | y is true if either x or y evaluates to true. As you mentioned, In your case `x.Status` can't be both, so one of the operands will be always true. – itaiy Mar 04 '20 at 17:33
  • The filtering is not working. I am still getting a record back that has a status of MessageDone and it should not come back – Baba Mar 04 '20 at 17:41
  • Maybe it changes after the filter? You can put a breakpoint on the setter of `Status` and check it. – itaiy Mar 04 '20 at 17:46