2 回答

TA貢獻1820條經(jīng)驗 獲得超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();
}
但是,對于生產(chǎn)中的使用,您可能希望確保param1和確實存在,并且還請查找并考慮和param2之間的差異。注意從中返回的值是裝箱的可能很有用。.Equals()==GetPropValue()

TA貢獻1859條經(jīng)驗 獲得超6個贊
考慮創(chuàng)建一個類似 LINQ 的擴展方法WhereAll,它執(zhí)行Where作為參數(shù)給出的所有謂詞:
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 關(guān)注
- 90 瀏覽
添加回答
舉報