按字符串数组过滤列表

时间:2013-02-18 13:53:58

标签: c# winforms

我有一个WinForms应用程序,我想在其中使用文本框来接收搜索查询(例如男士黑色T恤),然后根据此搜索查询过滤对象列表。

对象列表是订单对象。每个订单对象都有几个属性,如性别,大小,颜色等。

如果通过Space字符拆分搜索查询来获取字符串数组,那么搜索此字符串数组中每个项目的最佳方法是针对列表中每个订单对象中的每个属性,并返回那些匹配所有字符串数组中的字符串?

例如,如果我搜索“kids black medium”,我只想返回小孩和黑色和中等的订单,所以我不想只是黑色订单或只是孩子订单等。

2 个答案:

答案 0 :(得分:3)

给出以下Order类:

class Order
{
    public string Size {get; set;}
    public string Gender {get; set;}
    public string Colour {get; set;}
    public string Type {get; set;}

    // List of "searchable" properties
    public IEnumerable<string> GetTags()
    {
        return new []{Size, Gender, Colour, Type};
    }
}

一个简单的方法可能如下:

var list = new []
{
    new Order {Size = "large", Gender = "women", Colour = "red", Type = "tshirt"},
    new Order {Size = "large", Gender = "men", Colour = "black", Type = "tshirt"},
    new Order {Size = "medium", Gender = "kids", Colour = "black", Type = "tshirt"},
    new Order {Size = "medium", Gender = "kids", Colour = "black", Type = "shorts"},
    new Order {Size = "medium", Gender = "men", Colour = "black", Type = "tshirt"}
};

var searchString = "kids black medium";
var searchValues = searchString.Split(new []{" "}, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();

var result = from order in list 
             let tags = order.GetTags()
             where searchValues.All(s => tags.Any(t => t == s))
             select order;

result现在包含

enter image description here

您还可以使用IntersectHashSet来比较搜索值/代码,但如果没有有关要求All / Any的进一步信息,那么这些内容就足够了解决方案恕我直言。

答案 1 :(得分:1)

尝试以下方法:

class Item
{
    public bool Gender { get; set; }
    public int Color { get; set; }
    public string Type { get; set; }

    public string[] GetKeyWords()
    {
        // Return properties as array of key words.
        // You can cache the result for future use.
        return default(string[]);
    }
}

现在,如果您有项目列表和字符串数组(关键字),则可以编写以下查询:

var matches = from item in items
              let itemKeyWords = item.GetKeyWords()
              where keyWords.All(k => itemKeyWords.Any(c => c == k))
              select item;