假设以下代码
private readonly T entity;
public bool HasUnique<T>(Expression<Func<T, object>> property, IEnumerable<T> entities)
{
}
property
是T
实体的属性表达式。
如何检查entities
中是否有与[{1}}具有相同属性值的元素,而属性是从给定的属性表达式解析的?
到现在为止,我可以从实体
获取属性名称及其值问题似乎是如何在运行时设置并执行谓词?像
这样的东西entity
用法就像这样
Func<T, bool> predicate = // build a predicate
var isUnique = !entities.Any(predicate);
答案 0 :(得分:1)
我试图找出单词&#34; Unique&#34;与您描述的内容有关,并且您的示例用法并不涉及任何实体来比较people
的内容,但我认为您正在寻找类似的内容?
public static bool HasUnique<T>(this T referenceItem, Func<T, object> property,
IEnumerable<T> entities)
{
var referenceProperty = property(referenceItem);
return entities.Any(e => property(e) == referenceProperty);
}
或者这个:
public static bool HasUnique<T>(this T referenceItem, Func<T, object> property,
IEnumerable<T> entities)
{
var referenceProperty = property(referenceItem);
return entities.Any(e => property(e).Equals(referenceProperty));
}
甚至这个:
public static bool HasUnique<T, TProp>(this T referenceItem, Func<T, TProp> property,
IEnumerable<T> entities)
{
var referenceProperty = property(referenceItem);
return entities.Any(e => property(e).Equals(referenceProperty));
}
答案 1 :(得分:0)
您需要Expression<Func<T,object>>
吗?因为只需Func<T,object>
即可实现。
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqPlayground
{
class Program
{
public class UniqueChecker<T>
{
public bool HasUnique<T>(Func<T, object> property, IEnumerable<T> entities)
{
var uniqueDict = new Dictionary<object, bool>();
foreach (var entity1 in entities)
{
var key = property(entity1);
if (uniqueDict.ContainsKey(key))
{
uniqueDict[key] = false;
}
else
{
uniqueDict.Add(key, true);
}
}
return uniqueDict.Values.All(b => b);
}
}
public class Person
{
public string Name { get; set; }
}
static void Main(string[] args)
{
var people = new List<Person>
{
new Person {Name = "Chris"},
new Person {Name = "Janet"},
new Person {Name = "John"},
new Person {Name = "Janet"},
};
var checker = new UniqueChecker<Person>();
Console.WriteLine("Are names unique? {0}",checker.HasUnique(person => person.Name, people));
}
}
}