【问题标题】:C# query with filter condition带有过滤条件的 C# 查询
【发布时间】:2013-09-05 12:54:23
【问题描述】:

我有一个要过滤的 TransportType 列表 应用程序应该将用户选择与此列表进行比较,然后只返回他选择的应该在定义列表中的内容

 private static readonly string[] ValidTransportType = new string[]
    {
        "Cars", 
        "Airplans", 
        "Audi",
        "BMW", 
        "Airbus A333", 
        "Boing 747",
    };

    public static IEnumerable<string> GetSelectedTypes(IEnumerable<string> userSelection )
    {
        var list = (from transport in ValidTransportType
                    where userSelection.Contains(transport)
                    select transport).ToList();

        return list;
    }

例如:如果用户选择“Car”、“Porsche”,那么结果将只有“Car”,因为没有定义 porsche。

我的问题是,如何修改 Linq 查询以执行以下操作: 如果用户选择“Cars”、“Audi”、“BMW”,则查询返回 Cars,因为汽车包括 BMW 和 AUDI,如果用户选择“Audi”和“BMW”,则应用程序将返回“Audi”和“BMW”,但不返回“汽车”,因为它没有被选中,如果用户选择了“宝马”、“奥迪”、“飞机”、“波音 747”,那么应用程序应该返回“宝马”、“奥迪”、“飞机”的列表,而不是“波音” 747”,因为飞机包括“波音 747”

有什么想法吗?

编辑:

请注意,要比较的类型和类型在运行前是未知的,两者都来自外部文件,例如:在我的示例中,我放置了汽车,但它可以是动物、技术、人......等等,这就是为什么我无法预先预测类型并创建类。

【问题讨论】:

  • 在您当前的形式中,您在 Cars -> Audi、BMW 之间没有关系。考虑一个基类Cars,其子类为 BMW、Audi,或者一个字典结构,其中 BMW 和 Audi 具有 Car 的值,类似这样。
  • @Habib 感谢您的回复,问题是输入来自外部 csv 文件,要比较的列表也来自外部文件。它可以是汽车、动物等等,但总是有一个抽象类型,它是文件中每一行的第一个单词(汽车、飞机、动物……等)
  • 那么我建议使用Dictionary&lt;string,string&gt; 将每个项目作为键和值作为它们的类型。稍后您可以通过类型访问它们,但您必须在对象中建立关系才能获取相关数据。
  • 谢谢@Habib,其实这就是我正在做的,我正在使用字典 > 其中 List 是我要过滤的输入跨度>

标签: c# .net-3.5


【解决方案1】:

实际上没有 linq 查询会更容易,但使用普通的旧 foreach 循环。

首先,让我们创建一个字典,将BMWAudi 组合成一个Cars 组等:

var d = new Dictionary<string, List<string>>();
string[] items = {"Cars,BMW", "Cars,Audi", "Animals,Dog"};
foreach (var item in items)
{
    // TODO: use better variable names
    // you probably use a csv parser for this
    var s = item.Split(',');

    // fill the dictionary. 
    if (!d.ContainsKey(s[0]))
        d[s[0]] = new List<string>();
    d[s[0]].Add(s[1]);
}

那么,GetSelectedTypes 的实现可能如下所示:

public static IEnumerable<string> GetSelectedTypes(Dictionary<string, List<string>> validTypes, IEnumerable<string> userSelection )
{
    foreach (var kvp in validTypes)
        // if the key is in userSelection, only return the key, but no items
        if (userSelection.Contains(kvp.Key))
            yield return kvp.Key;
        // if not, only return valid items
        else 
            foreach (var item in kvp.Value)
                if (userSelection.Contains(item))
                    yield return item;
}

简单测试:

string[] userSelection = {"Cars", "Audi", "Dog"};
// will be [Cars, Dog], because Cars include Audi
GetSelectedTypes(d, userSelection);

string[] userSelection2 = {"BMW", "Audi", "Dog", "Animals"};
// will be [BMW, Audi, Animals] because Animals include Dog
GetSelectedTypes(d, userSelection2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-31
    • 2021-06-06
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多