The action method in the controller receive a value, like a couple of letters. The code checks if the table contains any of this letters. I'm using this code for that task:
var result = db.People.Where(b => b.Name.ToUpper().Contains(filter.ToUpper()));
But how can I check if the result variable is empty or null, when there are not any matching letters? I tested this, but it's not working!
If(result == ""){
// Do something
}
I would like to use Viewbag to send a message that there was no match or perhaps do this check in the View. I'm using this with some AJAX and Partial Views and it's working perfect, but I just want show a message if there are not any matches. What is the best way to check if the result value is empty or null?
The simplest way would be by using !result.Any():
var result = db.People.Where(b => b.Name.ToUpper().Contains(filter.ToUpper()));
If(!result.Any()){
// Do something
}
From MSDN on IEnumerable:
Any()
Determines whether a sequence contains any elements.
Fits exactly what you need.
Try this, Using FirstOrDefault it will give you the first record from the result, else if no result is yielded from the query it returns default value that is null,
var result = db.People.Where(b => b.Name.ToUpper().Contains(filter.ToUpper())).FirstOrDefault();
If(result == null){
// Do something
}
Or if you want to use this result, to manipulate something in your code then you can use the ToList(). It will return you list of values and if the query didnt yield anything then the list count will be 0.
var result = db.People.Where(b => b.Name.ToUpper().Contains(filter.ToUpper())).ToList();
If(result.Count == 0){
// Do something
}
Your code is not working because the code is returning an object not a string if you want to return a string then you have to use the "Select" clause to select a specific field and if you want to check in the same code then modify :
var result = db.People.Where(b => b.Name.ToUpper().Contains(filter.ToUpper())).ToList();
if(result != null && result.Count > 0)
it will work for you.
For IEnumerable we can use Any(), your code will can be written as
if(!db.People.Where(b => b.Name.ToUpper().Contains(filter.ToUpper())).Any() {
// do some thing
}
Related
When the DB Table is empty my request to access the result throws an error.
var resultEthnie = (from k in db.N_QONV
where k.qonv_fk_numvol == clientId &&
k.qonv_fk_eon_id == 64
select new { k.qonv_fk_num_question }
).Take(1);
return Convert.ToInt32(resultEthnie.FirstOrDefault().qonv_fk_num_question);
Is there a way to have a default return result value when the query result is empty?
Is there a way to have a default return result value when the query result is empty?
You are getting the error because you try to access the first element of the query result without check if it is empty or not.
To fix the issue use ? operator after the FirstOrDefault() method:
resultEthnie.FirstOrDefault()?.qonv_fk_num_question; // ? will escape accessing to
// qonv_fk_num_question if the result is null
However here I see a bit more elegant solution. Instead of using filtering, select and later trying to access the first element of the result, simple use FirstOrDefault() method lambda version:
var result = db.N_QONV.FirstOrDefault(k => (k.qonv_fk_numvol == clientId) &&
(k.qonv_fk_eon_id == 64));
return Convert.ToInt32(result?.qonv_fk_num_question);
When the linq query condition is not met, I'd expect a null to be returned from questions.FirstOrDefault() - but instead, an exception
Sequence contains no matching element
is thrown. Any ideas why?
var firstQ = questions.FirstOrDefault(a =>
a.Answers.Single(x => x.CourseAssignmentId ==
courseAssignmentId)?.Score == null) ?? questions.FirstOrDefault();
That's the difference between Single and SingleOrDefault.
Single throws an exception if there's any number of items different than 1 that match your predicate.
You should be using FirstOrDefault() instead. BTW you can combine the condition probably like
a.Answers.Single(x => x.CourseAssignmentId == courseAssignmentId && x.Score == null)
As others have already mentioned, it's the expected behavior of Enumerable.Single.
Anyway, it looks like an XY problem. Probably you should store the last scored question somewhere (e.g a dictionary).
That is, you could refactor your code as follows:
var assignmentScoredQuestionMap = new Dictionary<int, Question>();
// Fill the whole dictionary:
// You need to add for which assignment identifier you've answered a question
int assignmentId = 384;
// If the whole assignment exists, you set lastScoredQuestion, otherwise
// you set it to first question.
if(!assignmentScoredQuestionMap.TryGetValue(assignmentId, out var lastScoredQuestion))
lastScoredQuestion = questions.FirstOrDefault();
How do you index an IQueryable?
I am using a LINQ to sql query to get in values from a particular column. The query is as follows,
var intitalQuery = (from a in sql.GetTable<Staff_Time_TBL>()
where a.Info_Data == SelectedOption
select a.Staff_No).Distinct();
From there I want to be able index the intitalQuery variable and get values as needed.
That value is then used in another query.
My first try was this,
Column1.DataContext = sql.Staff_Time_TBLs.Where(item =>
item.Section_Data == SelectedOption &&
item.Staff_No == intitalQuery[0];
Then I tried this from here with no luck.
Column1.DataContext = sql.Staff_Time_TBLs.Where(item =>
item.Section_Data == SelectedOption &&
item.Staff_No == intitalQuery.First());
From what I can from the link is that that way gets just the first value, I want to be able to get all values via indexing. How do you go about that?
IQueryable<T> inherits from IEnumerable and as such has a wealth of extension methods to accomplish almost anything you'd need from a sequence. In particular, .ToList() turns an enumerable into a List<T> that allows efficient indexing.
.ToList() is slightly more efficient than the more obvious .ToArray() when working with sequences of unknown initial length, because .ToArray() requires an additional copy to end up with an array of exactly the right size. (But arrays are faster to loop over, so it all depends on what you're doing.)
You can do this:
public static List<Staff_Time_TBLs> GetIndexed(string staffNo){
var stuff = sql.Staff_Time_TBLs.Where(item =>
item.Section_Data == SelectedOption &&
item.Staff_No == staffNo;
return stuff.ToList();
}
//to use it...
initialQuery.ForEach(p=>{
var indexvalue = GetIndexed(p)
});
I have the following code:
IEnumerable<DestinationResult> destinations =
_repository.GetDestinationData();
IEnumerable<Destination> finalDestinations =
destinations.Select(GetAdditionalDestinationInfo);
private Destination GetAdditionalDestinationInfo(DestinationResult d){ /* CODE */}
How can I still use the method group call (Select(GetAdditionalDestinationInfo)) and filter out the null values that might be returned from GetAdditionalDestinationInfo (without having to call the method again to check for null in a where clause).
Something like:
IEnumerable<Destination> finalDestinations =
destinations.Select(GetAdditionalDestinationInfo != null)
Select maps input records to output records, one by one - there's no opportunity for filtering. Instead, you want to add another Where:
IEnumerable<Destination> finalDestinations =
destinations
.Select(GetAdditionalDestinationInfo)
.Where(i => i != null);
this code :
var allSubjectsForAStudent = GetAllSubjects<Subject>(studentId);
returns an
IEnumerable<Subject>
and I can see bunch of subjects returned in the debugger.
Want to check for a particular Subject doing a case insensitive comparison.
This is the code that I have:
var studentSubjects = allSubjectsForAStudent.Where(s => s.Name.Equals(subjectName, StringComparison.CurrentCultureIgnoreCase));
'subjectName' is a parameter that the method will recieve.
When this line executes I get the 'Object not set to an instance of an object' error.
So what I want to do is a CASE INSENSITIVE search and return the first item when there are more than one and return an empty collection when there are none.
Any clues?
Edit 1
The answers suggest that there can be an entry in the first collection which might have a 'null'. While the observation is true the program makes sure that the 'Subject Name' can not be a null value. Hope this helps.
Thanks in advance.
You could try:
var studentSubjects = allSubjectsForAStudent.Where(s => !string.IsNullOrWhiteSpace(s.Name) && s.Name.ToUpperInvariant() == subjectName.ToUpperInvariant()).FirstOrDefault();
This will either set studentSubjects to null or the first instance in the IEnumerable that matches.
You're getting a NullReferenceException when you call
s.Name.Equals(subjectName)
for an object where s.Name is null.
It will :
if(allSubjectsForAStudent!=null && !string.IsNullorEmpty(subjectName))
var studentSubjects = allSubjectsForAStudent.Where(s => s.Name.Equals(subjectName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();