c# - 找到最具体的匹配项目

标签 c# linq

用户输入将像'BY1 2PX',它将拆分并存储到如下列表中

var items = new List<string> {'BY1 2PX', 'BY12', 'BY1', 'BY'};

我有产品来源列表

public class Product
{
    public string Name {get;set;}
    public string Id {get;set;}
}

下面是示例产品列表。没有顺序保证,可以是任何顺序。

var products = new List<Product>{ 
    new Product("1", "BY1 2PX"),
    new Product("2", "BY12"),
    new Product("3", "BY1"),
    new Product("4", "BY"),
    new Product("5", "AA2 B2X"),
    //...etc
}

我的输出应该获取 1,因为它是最具体的匹配项。如果 Id = 1 不存在,那么它应该像那样获取 Id =2 ......等等 谁能帮我写一个 linq 查询。我试过类似下面的方法,这样可以吗?

var result =  items.Select(x => products.FirstOrDefault(p =>
                      string.Equals(p.Name.Trim(), x, StringComparison.OrdinalIgnoreCase)))
                   .FirstOrDefault();

最佳答案

好吧,您可以使用具有快速查找功能的字典:

var productsDict = products.ToDictionary(p => p.Name, p => p);

var key = items.FirstOrDefault(i => productsDict.ContainsKey(i));

Product result = key != null ? productsDict[key] : null;

或者如 Tim 所建议的,如果您有多个同名元素,您可以使用 Lookup :

var productsDict = products.ToLookup(p => p.Name, p => p);

var key = items.FirstOrDefault(i => productsDict.Contains(i));

Product result = key != null ? productsDict[key] : null;

关于c# - 找到最具体的匹配项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38745851/

相关文章:

c# - 我应该在后台线程中使用异步方法吗?

sql - LinqPad 不使用 C# 语句返回结果

c# - 获取 Entity Framework 中每个组的最后记录?

c# - Visual Studio 2015 Update 2 Web 应用程序(表单)编辑并继续不起作用

c# - 在 C# 中读取 WMV 分辨率

ffmpeg - 我可以使用 ffmpeg 将 JPEG 输出到内存流而不是文件吗?

C# 按字母顺序排序 a - z,然后排序为 aa、ab - zz

c# - linq to SQL Server 中的排序依据 (asc|desc) 以不同方式处理 DateTime

c# - 根据编号拆分字符串列表

c# - 从查询字符串请求值