LINQ where or C # filter

I have a collection returned by the web service. The property of this collection is "StatusCode", which is a string value that can be from 0 to 5 (don't ask me why it was configured as a string ... I don't schema this). Initially, I was going to use LINQ to filter this, and then realized that it was stupid (why return 100% of the records when I need 20%), and I parameterize my Stored Proc to do this for me.

In any case, I wrote a LINQ query that worked, but for the sake of curiosity, I assume there is a better way to do this:

var wo = from w in workOrders where w.StatusCode == "0" || w.StatusCode == "1" || w.StatusCode == "2" select w; 

Any suggestions? The correct answer goes to the most thorough answer - including documentation, best practices, etc.

+1
c # linq
source share
5 answers
 var wo = from q in workOrders where int.Parse(w.StatusCode) < 3 select w; 

This is a cleaner way to execute a LINQ query.

+2
source share
 var wo = from w in workOrders where new[]{"0", "1", "2"}.Contains(w.StatusCode) select w; 

By the way, if you used ORM, you could do it in LINQ (as above) and only pull 20% from the database;)

+2
source share

I recently wrote a post about a method using extension methods and parameters.

By adding this extension method to your code:

 public static bool IsIn<T>(this T source, params T[] values) { return values.Contains(source); } 

you can search as follows:

 var wo = from w in workOrders where w.StatusCode.IsIn("0", "1", "2") select w; 

It works on any type (as long as you create a good equals method). Any type of value for sure.

+2
source share

You can define the general extension method IsIn() :

 public static bool IsIn<T>(this T value, params T[] values) { return values.Contains(value); } 

Then you can write your request as follows:

 var wo = from q in workOrders where w.IsIn("1","2","3") select w; 
+1
source share

Your method is fine. I do not believe that search by search query or search is necessary for three string values โ€‹โ€‹(however this, of course, is not so). When parsing, I fear blank lines or zeros (even if we know that there should be lines only 0-5).

If you expect such filtering in other places, you should probably create a method (or extension) on WorkOrder that will determine the current state more expressively, for example

 public static bool IsNotCompleted(this WorkOrder workOrder) { return workOrder.Status == "0" || workOrder.Status == "1" || workOrder.Status == "2"; } 

and then

 var wo = from o in workOrders where o.IsNotCompleted() select o; 

or (I personally prefer this sitax)

 var wo = workOrders.Where(o => o.IsNotCompleted()); 

Using an extension to describe a state like this will increase readability, and in the future it will be much easier to add / remove status codes.

+1
source share

All Articles