سؤال

Please help me out with correct logic for predicate.

I have some list of products that i want to show in some regions that user specifies.

My Product class is next:

 public class Product
 {
    public int id { get; set; }
    public string name { get; set; }
    public List<string> regions { get; set; }
 }

And my settings class is:

public class LocalSettings
{
    public List<string> Regions { get; set; }
}

So the logic is next if user selected Region, for example, Europe then all Products with "public List<string> regions" containing Europe must be selected.

How should i write this in predicate correctly?

Here is my start point:

Predicate<Product> ProductFinder = (Product p) => { return DataManager.Instance.CurrentSettings.Regions.Contains(//HERE MUST BE ANY OF p.regions); };

Edit Question Number 1:

Thanks to help i have wrote this:

Predicate<Salesplay> SalesPlaysFinder = (Salesplay p) => { return DataManager.Instance.CurrentSettings.Regions.Intersect(p.regions).Any(); };

but my p.regions is a List i need to convert it to string

can i do something like .Intersect(p.regions.ToString()?

هل كانت مفيدة؟

المحلول

If I understand your question, you could use the Any and Contains methods like this:

Predicate<Product> ProductFinder = p => 
    DataManager.Instance.CurrentSettings.Regions.Any(r => p.regions.Contains(r))

Or you could use the Intersect and Any methods like this:

Predicate<Product> ProductFinder = p => 
    DataManager.Instance.CurrentSettings.Regions.Intersect(p.regions).Any()

For your updated question, if you want to test if a single string in the list, just use Contains by itself:

Predicate<Salesplay> SalesplayFinder = p => 
    DataManager.Instance.CurrentSettings.Regions.Contains(p.region)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top