是否可以从类列表创建最适合的 Linq 查询

本文关键字:Linq 查询 创建 列表 是否 | 更新日期: 2023-09-27 18:36:08

嗨,我有一个函数,它从集合中返回类的最佳拟合度。我知道如何使用 linq 查询替换 foreach 语句来获取新列表,但我想知道是否可以使用 linq 语句返回单个结果,该语句等同于类似于以下代码的最佳拟合。

private ProductDefaults GetBestFitProductDefault(Product product,IList<ProductDefaults> defaultList, ProductDefaultsTypeEnum type)
    {
        ProductDefaults pdef = null;
        var matches = -1;
        var bestfit = matches;
        foreach (var def in defaultList)
        {
            if(def.DefaultType == type)
            {
                matches = 0;
                if (def.Level1Ref == product.Level1Ref)
                {
                    matches++;
                }
                if (def.Level2Ref == product.Level2Ref)
                {
                    matches++;
                }
                if (def.Level3Ref == product.Level3Ref)
                {
                    matches++;
                }
                if (def.Level4Ref == product.Level4Ref)
                {
                    matches++;
                }
                if (def.Level5Ref == product.Level5Ref)
                {
                    matches++;
                }
                if (def.Level6Ref == product.Level6Ref)
                {
                    matches++;
                }
                if(matches > bestfit)
                {
                    bestfit = matches;
                    pdef = def;
                }
            }
        }
        return pdef;
    }

是否可以从类列表创建最适合的 Linq 查询

经过一些研究,我想出了这个 Linq 查询来替换代码,希望这将帮助可能需要类似解决方案的其他人。let 允许我创建一个新列,用于计算最佳拟合或匹配数。通过按最佳拟合降序对结果进行排序,我确信第一个对象将具有最高的最佳拟合值,因此我需要的对象也是如此。在这种情况下,可能会有多个产品具有相同的最佳拟合分数,选择哪一个是随机的,但就我而言,这是可以接受的。

private ProductDefaults GetBestFitProductDefault(Product product, IList<ProductDefaults> defaultList, ProductDefaultsTypeEnum type)
    {
        ProductDefaults pdef = null;
        var list =
                    from pd in defaultList
                    let bestfit = pd.Level1Ref == product.Level1Ref ? 1 : 0 +
                                  pd.Level2Ref == product.Level2Ref ? 1 : 0 +
                                  pd.Level3Ref == product.Level3Ref ? 1 : 0 +
                                  pd.Level4Ref == product.Level4Ref ? 1 : 0 +
                                  pd.Level5Ref == product.Level5Ref ? 1 : 0 +
                                  pd.Level6Ref == product.Level6Ref ? 1 : 0
                    where pd.DefaultType == type
                    orderby bestfit descending
                    group pd by bestfit into pdl
                    select new { pdl.Key, best = pdl.ToList() };
        pdef = list.First().best.FirstOrDefault();
        return pdef;
    }