Miranda Miranda - 1 month ago 7
C# Question

Search from the string array and ignore that exact matched string

how can I ignore the exact matched from the string array with linq query

here is my code whats wrong with it

public string GetItems(string SearchText, Int64 userID, Int64 orgID, Int64 locationID, string[] selectedProductName)
{
List<Product> searchList = new List<Product>();
string jsonText = "";
try
{
searchList = dbContext.usp_ang_GetProductList_(orgID, SearchText, locationID, 0).ToList();
var abc = searchList.Where(a => a.Name.Any(a.Name != selectedProductName).ToList();
jsonText = JsonConvert.SerializeObject(abc);
}
catch (Exception ex)
{

}
return jsonText;
}

Answer

Your use of the .Any is incorrect:

  1. In your current use you are checking if any of the chars that construct a.name match some predicate.
  2. .Any(a.Name != selectedProductName) - you need to form a properly formatted lambda expression

You want to check if any of the values of the selectedProductName array is equals to the a.Name.

var abc = searchList.Where(a => !selectedProductName.Any(name => name == a.Name)).ToList();

Because selectedProductName is a string[] it is cleaner just to use .Contains:

var abc = searchList.Where(a => !selectedProductName.Contains(a.Name)).ToList();

Also it is a shame to bring all that data from the database just to filter it the row after. If you remove the ToList() the filtering will happen in the database:

var abc = dbContext.usp_ang_GetProductList_(orgID, SearchText, locationID, 0)
                   .Where(a => !selectedProductName.Contains(a.Name)).ToList();