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

时间:2014-09-19 15:43:11

标签: c# linq loops

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

╔═════════════╦═════════════════╗
║ 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)

1 个答案:

答案 0 :(得分:2)

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

var namesToMatch = GetIdentityNamePatterns(type);

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