How to detect data returned in a C # LINQ query

I make a second request below, incremented by 'a' and 'b' ('b' increases to the limit, then reset and 'a' increases). There may be several lines with the given values ​​"a" and "b".

struct MyData {int mdA; int mydB; } .... int find_next_a(int a, int b) { var q = from p in db.pos where (pa >= a && pb > b) || (pa > a && pb > 0) orderby pa, pb select new MyData { mdA = pa, mdB = pb }; return q.First().mdA; // ERROR: InvalidOperationException at end of data } 

The query works until I get to the end of the table. Then I get an InvalidOperationException. I cannot call q.Count () because I get the same exception.

How can I find that q does not have any reliable data in it?

[ EDIT :] Thanks Jon Skeet (and Bojan Skrchevski, Bodrick), I post the solution above.

 int find_next_a(int a, int b) { var q = from p in db.pos where (pa >= a && pb > b) || (pa > a && pb > 0) orderby pa, pb select new { pa, pb }; var result = q.FirstOrDefault(); // catch running past end of table if (result == null) return -1; return q.First().a; // return real data } 
+4
source share
3 answers

Instead, you can use FirstOrDefault :

 var result = q.FirstOrDefault(); if (result == null) { // Query results were empty } 

Note that there is no way to tell between the β€œreal result, which is the default value for the item type” and β€œno results” ... this is not a problem here, since all your real results are non-zero references, but it is worth knowing.

EDIT: I did not notice that you used a custom structure; I would not read it correctly as an anonymous type. I highly recommend using an anonymous type here instead of a mutable structure. Or, given that you only need mdA , you can use:

 var q = from p in db.pos where (pa >= a && pb > b) || (pa > a && pb > 0) orderby pa, pb select (int?) pa; int? result = q.FirstOrDefault(); if (result == null) { // No results - take whatever action } else { // Got a result - find the underlying value... int a = result.Value; } 
+9
source

Instead of First() use FirstOrDefault() , and then check the null value before using it.

 var rResult = q.FirstOrDefault(); if(rResult != null) { var something = rResult.mda; } 
+3
source

You can use FirstOrDefault () to avoid an InvalidOperationException. In the following example, x will be null if q has no elements. Then you can check it out and continue accordingly.

 var x = q.FirstOrDefault (); return x == null ? -1 : x.mdA; 
+2
source

Source: https://habr.com/ru/post/1394363/


All Articles