hor*_*ace 5 .net linq generics
我必须向我的C#.NET应用程序添加一些"查找"查询.基本上,会有许多表,它们都具有相同的模式,但包含不同的值.
我面临着反复编写相同的代码(应该是一个OO方式来做到这一点......)
[编辑 - 以下内容经过修改以显示更完整的信息]无论如何,我想做的是:
public List<GenericLookupE> GetLookupItems( string what )
{
// create db thing
if ( "regions" == what ) return FetchLookup( db.lkRegions.AsQueryable() );
if ( "partners" == what ) return FetchLookup( db.lkPartners.AsQueryable() );
if ( "funders" == what ) return FetchLookup( db.lkFunders.AsQueryable() );
return null; // or something more intelligent than that =)
}
private List<GenericLookupE> FetchLookup<T>( IQueryable<T> lookup )
{
return lookup.OrderBy( p => p.Sequence ).Select
( p => new GenericLookupE()
{
ID = p.ID
,Label = p.Label
,StateCode = p.StateCode
,Sequence = p.Sequence
}
).ToList();
}
Run Code Online (Sandbox Code Playgroud)
当然,问题是编译器不知道'p => p.Sequence'是什么.有任何想法吗?
谢谢你们.
将公共接口添加到您的\xd0\xa2类中,Sequence在其中进行定义,然后向通用需求参数添加约束\xd0\xa2以实现公共接口。
interface ICommonInterface { // This is an awful name, please pick something better\n int Sequence { get }\n}\n\nprivate List<GenericLookupE> FetchLookup<T>( IQueryable<T> lookup ) where T : ICommonInterface {\n // Your stuff here\n}\nRun Code Online (Sandbox Code Playgroud)\n