I have a string parameter 'type' to my method, which can be null, single value or multiple values separated by comma as follows:
string type=null; //should return all rows
string type="java"; //should return data with java
string type="xamarin,java,c#"; //should return data with all these 3 options
string type="invalid"; //should return null
I need to return all rows if type is empty else return only the rows matching the string array.
I am using following LINQ in my server side cs file:
public object filter(string type)
{
var models = context. /// get data from db, with id,Date,type,comment as columns
return models.Where(v=> string.IsNullOrEmpty(type) ? true : type.Split(',').Contains(v.type)
.OrderByDescending(a => a.Date).ToList();
}
When i pass null, it returns all row - seems working
When i pass type separated by comma, it return rows of all types - seems working
When i pass invalid type, it should return zero rows (Not working)
I am expecting a clean and single line solution.
You want this result
string type="invalid"; //should return null
but in you code this condition is not processed
return type.Split(',').Contains("invalid") ? null : models
.Where(v=> string.IsNullOrEmpty(type) ? true : type.Split(',').Contains(v.type)
.OrderByDescending(a => a.Date)
.ToList();
谢谢朋友,它适用于任何情况。
return models.Where(v => string.IsNullOrWhiteSpace(type) ? true : type.Split(',').Contains(v.type) ).OrderByDescending(a => a.Date).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.