如何重载方法以接受Linq表达式
本文关键字:Linq 表达式 方法 何重载 重载 | 更新日期: 2023-09-27 18:28:53
设置
我有一个名为WhereIn()的方法,它接受params对象[]值:
public bool WhereIn(params object[] values)
问题
不幸的是,调用WhereIn(values.Select(v => v.Id))
很容易出错。
这会导致传递一个Linq表达式,而不是将值枚举到数组中。如何重载我的方法以接受linq表达式?
我的最佳猜测
我目前的最佳猜测是制作一个IEnumerable重载,然后必须检查它是否是一个字符串,然后将该字符串填充到一个对象数组中以调用另一个重载:
public bool WhereIn<T>(IEnumerable<T> values){
if(values.GetType().Name == "String"){
return WhereIn(new object[]{values});
} else {
// Do Stuff
}
}
对于必须手动检查字符串类型,我真的很不高兴,而且我担心我可能会错过其他一些实现IEnumerable的类,这些类应该封装在对象数组中。
如果您有以下两个签名:
public bool WhereIn<T>(params T[] values);
public bool WhereIn<T>(IEnumerable<T> values);
你这样称呼它:
WhereIn("hi")
这将调用第一个方法,并将单个元素string[]
传递给它。
您可能想要检查System.Collections.Generic.Contains()
方法,并在尝试"重新发明轮子"时省去不必要的麻烦。
如果你做了这样的事情。。。编辑:我提供了一个测试方法,如果你想要,你可以尝试不同的选择(a=>a.Id)
[TestMethod]
public void Test()
{
var test = new[] {
new { Id = 1, Name = "John" },
new { Id = 2, Name = "George" },
};
if (WhereIn(test.Select(a => a.Name)))
{
}
}
//Works with value types, strings, and classes
public bool WhereIn<T>(IEnumerable<T> values)
{
var objectArray = new object[values.Count()];
for (int index = 0; index < values.Count(); index++)
{
objectArray[index] = values.ElementAt(index);
}
return WhereIn(objectArray);
}
// This was just for test purposes
public bool WhereIn(params object[] values)
{
return true;
}
我已经在Visual studio测试中运行了这个,并且似乎可以工作。
希望这能有所帮助。
我还没有试过,但你能不能不做
WhereIn(values.Select(v => v.Id).ToArray<Type_of_Value>())
其中Type_of_Value是值集合中使用的类型