Home > database >  C# - Does FirstOrDefault() return null in this case?
C# - Does FirstOrDefault() return null in this case?

Time:11-22

I hope this question respects the StackOverflow guidelines. I have a table (ResultsTable) in my DB (SQL Server management studio) in which the columns are:

ID (PK, FK, int, not null)
RiskRate (PK, int, not null)
FileName (PK, nvarchar(100), not null)

In C# I've used EF. In my code, there is a method SelectFileNames(string fileName):

    var resultSearch = (from result in DB.ContextManagement.ResultTable
                        where result.FinaName.compareTo(fileName) == 0
                        select result).FirstOrDefault();
    if (resultSearch == null)
         ...
    else
         ...

The FirstOrDefault() method has this description:

 Returns the first element of the sequence that satisfies a condition
 or a default value (TSource) if no such element is found. 

So, how can I force FirstOrDefault() to return null if there isn't an element with that filename? NB: in my table ResultTable, the columns have the not null constraint.

Thanks.

CodePudding user response:

try like this .

enter image description here

            List<Users> userlist = new ();

            userlist.Add(new Users() {username = "testuser",password = "testpass"});
            userlist.Add(new Users() { username = "testuser2", password = "" });


            var result = userlist.FirstOrDefault(s => s.username == "testuser2")?.password;

CodePudding user response:

If in your query

(from result in DB.ContextManagement.ResultTable
                        where result.FinaName.compareTo(fileName) == 0
                        select result)

no entity respect your condition then the FirstOrDefault will return null.

It is specified in the documentation

"Remarks The default value for reference and nullable types is null."

Since the type of result is a reference type it will return null.

CodePudding user response:

You can use the following syntaxe

var resultSearch = DB.ContextManagement.ResultTable.Where(x => x.FileName == fileName).ToList() ;
if (resultSearch.Count > 0)
     ...
else //Get the first element of list
  • Related