gpt4 book ai didi

c# - 我怎样才能使这些方法通用?

转载 作者:太空狗 更新时间:2023-10-30 01:15:09 26 4
gpt4 key购买 nike

我有的是一些字典,都是这种类型

Dictionary<Guid, string>

我有很多方法基本上做同样的事情,但使用不同的参数来过滤各种东西。这里有几个示例方法

private IQueryable<SomeClass> FilterContacts(Filter filter,
IQueryable<SomeClass> query)
{
if (filter.Contacts != null && filter.Contacts.Any())
{
result = result.Where(x => filter.Contacts.Contains(x.ContactID));
}

return result;
}

private IQueryable<SomeClass> FilterSomethingElse(Filter filter,
IQueryable<SomeClass> query)
{
if (filter.SomethingElse != null && filter.SomethingElse.Any())
{
result = result.Where(x => filter.SomethingElse.Contains(x.SomethingElseID));
}

return result;
}

所以它们所有这些方法共享相同的结构,但在过滤器和 where 子句中使用不同的属性。有没有一种方法可以使它足够通用,以至于我只能使用一种方法来做到这一点?

最佳答案

以下解决方案使用委托(delegate)作为参数来注入(inject)一些必要的逻辑,使方法更通用。

private IQueryable<SomeClass> FilterCommon(IQueryable<SomeClass> query
, Filter filter
, Func<Filter, Dictionary<Guid, string>> getDictionary
, Func<SomeClass, Guid> getKey)
{
IQueryable<SomeClass> result = null;
Dictionary<Guid, string> commonDictionary = getDictionary(filter);
if (commonDictionary != null && commonDictionary.Any())
{
result = query.Where(x => commonDictionary.ContainsKey(getKey(x)));
}

return result;
}

我认为 Filter 参数不是必需的,因此可以简化为:

private IQueryable<SomeClass> FilterCommon(IQueryable<SomeClass> query
, Dictionary<Guid, string> commonDictionary
, Func<SomeClass,Guid> getKey)
{
IQueryable<SomeClass> result = null;
if (commonDictionary != null && commonDictionary.Any())
{
result = query.Where(x => commonDictionary.ContainsKey(getKey(x)));
}

return result;
}

用法:

//Initializing a few things first...
Filter myFilter = new Filter();
IQueryable<SomeClass> query = new Queryable();//Just a generated type

//This is for my first example from above
FilterCommon(query, myFilter, x => x.Contacts, x => x.ContactID);

//Second example without filter parameter
FilterCommon(query, myFilter.Contacts, x => x.ContactID);
FilterCommon(query, myFilter.SomethingElse, x => x.SomethingElseID);

关于c# - 我怎样才能使这些方法通用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39682155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com