Click here to Skip to main content
15,895,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to check if a bit value is false but I cannot seem to make this work.
I am connected to a database and am working with entity framework.
I am generating a list with a method 'GetAll()', which returns a full list of the forms in the database. I am then trying to create a foreach list that checks if the deleted field is true or false.

It is important to mention that in my sql database, the value of type bit can be null.

What I have tried:

public List<Form> GetAllForms()
{

    var list = GetAll();
    List<Form>filteredList = new List<Form>();

    foreach(var item in list)
    {
        bool checkingDelete = Convert.ToBoolean(item.Deleted);
        if(checkingDelete == false)
        {
                filteredList.Add(item);
        }

    }
Posted
Updated 8-Oct-20 23:16pm

1 solution

Assuming the property on your Form entity is declared as bool? or Nullable<bool>, you can't use Convert.ToBoolean if the value is null.

Instead, compare the value to true or false:
C#
foreach (var item in list)
{
    if (item.Deleted == false)
    {
        filteredList.Add(item);
    }
}

// Or, using LINQ:
List<Form> filteredList = list.Where(item => item.Deleted == false).ToList();
NB: Values which are null will not be equal to false, so those items will be included in the filtered list. If you want to exclude them, you can either change your condition:
C#
List<Form> filteredList = list.Where(item => item.Deleted == false || item.Deleted == null).ToList();

// Or:
List<Form> filteredList = list.Where(item => item.Deleted != true).ToList();
Or you can coalesce the nullable value:
C#
List<Form> filteredList = list.Where(item => item.Deleted.GetValueOrDefault() == false).ToList();

// Or:
List<Form> filteredList = list.Where(item => !item.Deleted.GetValueOrDefault()).ToList();

// Or:
List<Form> filteredList = list.Where(item => (item.Deleted ?? false) == false).ToList();

// Or:
List<Form> filteredList = list.Where(item => !(item.Deleted ?? false)).ToList();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900