2 回答
TA贡献1820条经验 获得超10个赞
似乎您想要的是比较通过成员变量的名称访问的成员变量。这称为反射。这是我的解决方案:
首先添加一个扩展方法来帮助我们通过名称获取成员变量(来自this SO answer):
static class Extension
{
public static object GetPropValue(this object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
}
然后,您的功能将是:
public static bool CheckDuplicate<T>(IEnumerable<T> list, object obj, string param1, string param2)
{
return list.Any(item =>
item.GetPropValue(param1).Equals(obj.GetPropValue(param1)) &&
item.GetPropValue(param2).Equals(obj.GetPropValue(param2))
);
}
我用这个测试了这个功能。它打印True:
static void Main(string[] args)
{
var theList = Enumerable.Range(0, 10).Select(i => new Tuple<int, int>(i, i + 1));
Console.WriteLine(CheckDuplicate(theList, new { Item1 = 5, Item2 = 6 }, "Item1", "Item2"));
Console.ReadKey();
}
但是,对于生产中的使用,您可能希望确保param1和确实存在,并且还请查找并考虑和param2之间的差异。注意从中返回的值是装箱的可能很有用。.Equals()==GetPropValue()
TA贡献1859条经验 获得超6个赞
考虑创建一个类似 LINQ 的扩展方法WhereAll,它执行Where作为参数给出的所有谓词:
static IEnumerable<TSource> WhereAll<TSource>(this IEnumerable<TSource> source
IEnumerable<Func<TSource, bool>> predicates)
{
// TODO: exception if source / predicates null
// return all source elements that have a true for all predicates:
foreach (var sourceElement in source)
{
// check if this sourceElement returns a true for all Predicates:
if (predicates.All(predicate => predicate(sourceElement))
{
// yes, every predicate returns a true
yield return sourceElement;
}
// else: no there are some predicates that return false for this sourceElement
// skip this element
}
用法:
List<Person> persons = ...
// Get all Parisians with a Name that were born before the year 2000:
var result = persons.WhereAll(new Func<Person, bool>[]
{
person => person.Name != null,
person => person.BirthDay.Year < 2000,
person => person.Address.City == "Paris",
});
- 2 回答
- 0 关注
- 105 浏览
添加回答
举报
