简体   繁体   中英

Filtering a List with an array items

i need to filter a list with strings in an array. Below code doesn't return the expected result.

List<searchModel> obj=//datasource is assigned from database

mystring="city1,city2";
string[] subs = mystring.Split(',');
foreach (string item in subs)
{
    obj = obj.Where(o => o.property.city.ToLower().Contains(item)).ToList();
}

As far as you're using Contains , I'd say you could be trying to get

  1. entries, city of which matches any city from mystring
  2. entries, city of which match all cities from mystring

So, having (I simplified searchModel class, having omitted property ):

List<searchModel> obj = new List<searchModel>
{
    new searchModel{city = "city1"},
    new searchModel{city = "city2"},
    new searchModel{city = "city3"}
};

var mystring = "city1,city2";
var subs = mystring.Split(',').ToList(); //let it be also List<T>

We can do:

//the 1st option
var orFilter = obj.Where(o => subs.Any(s => o.city.ToLower().Contains(s)))
                  .ToList();
//the 2nd option
var andFilter = obj.Where(o => subs.TrueForAll(s => o.city.ToLower().Contains(s)))
                   .ToList();

Then do a simple check

foreach (var o in andFilter)
{
    Console.WriteLine(o.city);
}

I'd say that the OP is equal to option 2, not option 1.

I think you want this, or something close - I haven't tested it:

List<searchModel> obj=//datasource is assigned from database

mystring="city1,city2";

string[] subs = mystring.Split(',');

obj = obj.Where(o => subs.Contains(o.property.city.ToLower())).ToList();

What you're currently doing is filtering the list by ALL cities. So you'll only return results where o.property.city equals "city1" and "city2" (and any other cities you might have in the list). So you won't get any results.

To match any city in the list instead, try this:

var myFilteredObj = obj.Where(o => subs.Contains(o.property.city.ToLower()).ToList();

I add this codes of lines, probably will help someone and maybe someone will optimize it:

var jaggedArray = new string[100][];
var i = 0;
jaggedArray[i] = {"first folder","first file","first 5 files","last 5 folder"};
filter = "irs le";
var arrFilters = filter.Split(' ');
foreach (var arrFilter in arrFilters)
{
    jaggedArray[i] = jaggedArray[i].Where(p =>p.ToLower().Contains(arrFilter.ToLower())).ToArray();
    jaggedArray[i + 1] = jaggedArray[i];
    i++;
}
return jaggedArray[i]; //new array after filter
//result: "first file","first 5 files"
var result = obj.Where(piD => subs.Contains(piD.city)).ToList();

上面的代码将基于字符串数组过滤obj List

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM