选择出现在两个列表中的单个元素

本文关键字:列表 两个 元素 单个 选择 | 更新日期: 2023-09-27 18:23:41

我需要从属性列表中按名称找到一个属性,该属性与另一个列表中的字符串相匹配,该列表是根据声明类型的类型生成的。

╔═════════════╦═════════════════╗
║ Properties  ║      Names      ║
╠═════════════╬═════════════════╣
║ User.UserId ║ Id              ║
║ User.Name   ║ IdUser          ║
║ User.Age    ║ UserId <- MATCH ║
║ User.Email  ║ Key             ║
║             ║ UserKey         ║
║             ║ KeyUser         ║
╚═════════════╩═════════════════╝

private const string IdAffix = "Id";
private const string KeyAffix = "Key";
private static readonly Func<Type, IEnumerable<string>> GetIdentityNamePatterns
    = type => new [] { IdAffix, KeyAffix, type.Name + IdAffix, IdAffix + Type.Name,...}
private Expression<Func<TEntity, TIdentity> KeySelector = entity =>
{
    var type = typeof(TEntity);
    if(type.IsAssignableFrom(typeof(IEntity<TIdentity>)))
        return ((IEntity<TIdentity>) entity).Id;
    const BindingFlags bindingFlags
        = BindingFlags.IgnoreCase | BindingFlags.GetProperty | BindingFlags.Public;
    var properties = type.GetProperties(bindingFlags);
    var identityProperty = entityProperties.SingleOrDefault(x =>
        Attribute.IsDefined(x, typeof(IdentityAttribute)) && x.PropertyType == typeof (TIdentity))
        // this is where I'm stuck
        // how to loopthe list of possible names while looping
        // through the properties at the same time?
        ?? entityProperties.SingleOrDefault(
            x => x.Name.Equals... // GetIdentityNamePatterns(type)

选择出现在两个列表中的单个元素

我不能100%确定你的意思-基本上,你想返回某个对象的属性-该属性的名称存在于其他列表中吗?

var namesToMatch = GetIdentityNamePatterns(type);
var property = entityProperties
    .FirstOrDefault(p => namesToMatch.Any(n => x => x.Name.Equals(n)));