Seems like what you want is to compare member variables accessed by the name of the member variable. This is known as reflection. Here is my solution:
First add an extension method to help us get member variables by name (from this SO answer):
static class Extension
{
public static object GetPropValue(this object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
}
Then, your function would be:
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))
);
}
I tested the function with this. It prints 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();
}
For use in production, however, you might want to ensure that the param1
and param2
actually exist, and also please lookup and consider the differences between .Equals()
and ==
. It might be useful to note that the returned values from GetPropValue()
are boxed.