首页 > 解决方案 > 在列表 C# 中查找最佳匹配实例的最佳实践

问题描述

对于你们大多数人来说,这肯定是一个非常简单的问题。但我目前正在努力寻找解决方案。

想象一下,您有一个猫列表(列表),其中每只猫都有一个婴儿列表(小猫)

public class Cat
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Race { get; set; }
        public bool Gender { get; set; }
        public List<Kitten> Babys { get; set; }  
    }

public class Kitten
    {
        public string Name { get; set; }
        public double Age { get; set; }
        public bool Gender { get; set; }
    }

现在我想找到最符合给定要求的猫。很容易出现猫只满足 3 个要求中的 2 个的情况。我只是想找到最符合我要求的猫。

我的要求可能是:

我的实际解决方案是比较所有属性并选择匹配属性数量最多的属性。但这不是通用的,我相信有更好的方法来做到这一点。

提前致谢

标签: c#listmatching

解决方案


好吧,我没有机会测试这个解决方案,但你可以试试这个:

假设您有一个猫列表:

var cats = new List<Cat>();

现在您已经定义了您的标准:

var desiredName = "Micky";
var desiredAge = 42;
var desiredKitten = "Mini";

然后你必须得到你想要的猫:

var desiredCat = cats
        .Select(c => new {
            Rating = 
                Convert.ToInt32(c.Age == desiredAge) +       // Here you check first criteria
                Convert.ToInt32(c.Name == desiredName) +     // Check second
                Convert.ToInt32(c.Babys.Count(b => b.Name == desiredKitten) > 0),   // And the third one
            c })
        .OrderByDescending(obj => obj.Rating) // Here you order them by number of matching criteria
        .Select(obj => obj.c) // Then you select only cats from your custom object
        .First(); // And get the first of them

请检查这是否适合您。如果您需要更具体的答案或一些编辑供我添加。


推荐阅读