This question already has answers here:
C# compiler error: "not all code paths return a value"
(9 answers)
Closed 2 years ago.
I have a task to find even or odds numbers in a list using LINQ lambda.
I simply have this code to do it, but the compiler says "not all code paths return a value in lambda expression". So I think I need a default value, but how can I implement it? I tried a few things but still don't work. Please give advice. Thanks.
list = list.Where(x =>
{
if (command == "odd")
return x % 2 != 0;
else if (command == "even")
return x % 2 == 0;
});
If the command is "notEvenOrOdd" what should be the result? The example code does not cover this case, and it will therefore fail.
Using a "command" to determine what to do is usually not a great design. An alternative would be two extension methods:
public static IEnumerable<int> WhereEven(this IEnumerable<int> list) => list.Where(x => x % 2 != 0);
public static IEnumerable<int> WhereOdd(this IEnumerable<int> list) => list.Where(x => x % 2 == 0);
You can then check the command outside the lambda and run one of the methods above depending on the result.
I meant if the if-else statement dont match the conditions. I tried this and it works.
list = list.Where(x =>
{
if (command == "odd")
return x % 2 != 0;
else if (command == "even")
return x % 2 == 0;
return false;
}).ToList();
Sometimes the elements that I am checking against do not exist and the application throws an error.
if(responseSerialNumber.ElementAt(1) == 0)
{
//Do the following
}
How can I do deal with this?
There are 2 ways of solving this problem.
First, just check if the array has enough elements before accessing:
if(responseSerialNumber.Length > 2 && responseSerialNumber.ElementAt(1) == 0)
{
//Do the following
}
The second way is to use ElementAtOrDefault() which returns the appropriate default value based on the type of the array.
var item = responseSerialNumber.ElementAtOrDefault(1);
if (item != default(byte)) { // or use "(item != null)" if item is an reference type
//Do the following
}
BEWARE: The second solution would work fine if you have an array of non-value types (in this case they can have null as default value). If you have byte array, stick with the first solution.
If responseSerialNumber is an array byte[] (see comments) you can check the array: first for its Length then for the value
if (responseSerialNumber.Length >= 2 && responseSerialNumber[1] == 0) {
...
}
Or (for arbitrary indexAt and valueToTest):
if (responseSerialNumber.Length >= indexAt + 1 &&
responseSerialNumber[indexAt] == valueToTest) {
...
}
In general case (when responseSerialNumber is IEnumerable<T>) for given
int indexAt = 1;
valueToTest = 0;
we can Skip indexAt items and check the very next one:
if (responseSerialNumber.Skip(indexAt).Take(1).Any(item => item == valueToTest)) {
// responseSerialNumber has at least indexAt items
// indexAt's items is equal to valueToTest
}
Or even
if (responseSerialNumber.Where(index, value) =>
index == indexAt && value == valueToTest)) {
...
}
I'm having an error when I'm trying to request data with Linq and entity framework.
Below, the following:
verif = context.DeviceVerifications.Where(d => d.phone == phone
&& d.securityKey == key
&& d.validated == 0
&& (((TimeSpan)(DateTime.Now - d.createDate)).Minutes <= 30)).FirstOrDefault();
The error that shows up is the following: DbArithmeticExpression arguments must have a numeric common type.
I think that the problem comes from that part of the request ((TimeSpan)(DateTime.Now - d.createDate)).Minutes <= 30) but there are the same type on both sides of the comparison.
Does somebody can help me with that ?
Thanks in advance !!
I am not sure whether the ((TimeSpan)(DateTime.Now - d.createDate)).Minutes <= 30) expression can be correctly converted to a storage query.
I would use the DbFunctions.DiffMinutes method
verif = context.DeviceVerifications.Where(d => d.phone == phone
&& d.securityKey == key
&& d.validated == 0
&& DbFunctions.DiffMinutes(DateTime.Now, d.createDate) <= 30)).FirstOrDefault();
Arithmetic with DateTime is not supported in Entity Framework, you have to use DbFunctions.DiffMinutes instead. According to the documentation, when used as part of a LINQ to Entities query, this method invokes the canonical DiffMinutes EDM function to calculate the number of minutes between two time spans.
I have been scratching my head with this error for at least an hour, what the heck is wrong here?
In a loop:
if (selectedItems[x].ImageIndex == 3)
{
List<ListViewItem> dupes = CP.listCache.FindAll(delegate(ListViewItem item) { return item.Text == selectedItems[x].Text; });
if (dupes != null && dupes.Count == 1)
dupes[0].ImageIndex = 0;
}
I can access the imageIndex, but not set it. ArgumentOutOfRange exception occurs.
Make sure you know what what's throwing your ArgumentOutOfRange exception -- that's your first problem. Is x a valid index into selectedItems? Is the index you're setting into your image list valid? Remember, indexes are zero-based, not 1-based.
I stumbled upon this while doing a review and the author is not available:
int n = Convert.ToInt32(text);
if (((n > 0) || (n < 0)) || (n == 0))
{
return 1;
}
The code in general looks solid and it's hard for me to believe that the only purpose of this snippet is to confuse reviewers, but I don't see a way for this condition to fail. Am I missing something?
This may be a remnant of a nullable type. See here at msdn for an explanation, but basically if your code was originally this:
int? n = StringToInt(text); // People roll their own functions to do this, though
// they really shouldn't
if (((n > 0) || (n < 0)) || (n == 0))
{
return 1;
}
Then this could possibly fall through. Each of the statements above would be false, as n could be null from the function, assuming it returned null on a bad input, and the code supported nullable types.
Unlikely, but when looking at "maintained code" anything is possible. But as written, it MUST return 1 (or throw an exception, as mentioned by others in this thread).
It will always return true, assuming it gets there.
Consider:
bool x = (n > 0) || (n < 0);
bool y = (n == 0);
if (x || y)
{
return 1;
}
If n is not zero then either n > 0 or n < 0 is true, so x is true and y is false.
If n is zero, n == 0 is true, so x is false and y is true.
Either way, one side of the OR is true.
That sure looks like a 100% true statement to me. All those parentheses shouldn't matter in the least, since || is associative, i.e.,
(a || b) || c == a || (b || c) == a || b || c
If you overload the relational operators for your class, it might be the case that the condition evaluates to false, but since n is an int, it always evaluates to true
It's possible that int n = Convert.ToInt32(text); could throw an exception, in which case the if statement never even gets evaluated.
See Convert.ToInt32() on MSDN.
As above, it will always be true because, by definition, any real number is either zero, less than zero or greater than zero, and you have covered all cases in your code.
Always will be 1, unless Convert.ToInt32(text) throws an exception.
I don't see how it can evaluate to false.
If, however, n was declared at a different scope where more than a single thread had access to it and one of these threads changes its value, theres quite a high chance the condition would fail.
it will always be true as you write all the states it might be (e.g < > ==)
Yes, it could also throw an exception if the conversion fails :-)