c# - 在列表 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 个的情况。我只是想找到最符合我要求的猫。
我的要求可能是:
- 名字必须是“Micky”
- 年龄是 42
- 有一只名叫“Mini”的小猫
我的实际解决方案是比较所有属性并选择匹配属性数量最多的属性。但这不是通用的,我相信有更好的方法来做到这一点。
提前致谢
解决方案
好吧,我没有机会测试这个解决方案,但你可以试试这个:
假设您有一个猫列表:
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
请检查这是否适合您。如果您需要更具体的答案或一些编辑供我添加。
推荐阅读
- javascript - 离子输入文本框应该可见,直到选中运输复选框
- javascript - 为什么 Moment.js 在给定时区的第二天返回?
- javascript - 在角度 9 的 elemntRef 中找不到 Div 的内部文本
- android - android片段没有填满整个屏幕
- apostrophe-cms - 我可以更改 apos-area 及其小部件的包装器元素吗?
- android - 我想使用Android App从firebase中单独获取所有数据
- android - “android:windowLightStatusBar”不起作用
- vue.js - 在 Quasar/Vue 中触发/更新从子组件到父组件的数据更改,以防子组件具有项目列表
- java - 禁用 Spring Cloud 配置客户端
- javascript - 如何使用 Vue CLI 一次将多个 Vue.js 组件构建为原生 Web 组件?