[英]How to make a method that returns an IEnumerable of anonymous types
在我們的環境中,我們有很多大型業務對象。 我們使用自己的數據庫訪問層(在此示例中簡化為'Db'類)。 有時,我們希望檢索業務對象中可用屬性的選定部分的列表(例如,僅查看客戶的ID和姓氏)。
在Entity框架中,我可以使用以下內容:
var keyValues = context<Customer>.Select(c => new { Id = c.ID, LastName = c.LastName, City = c.City })
但正如我之前所說,我們不是使用Entity FrameWork而是使用我們自己的數據訪問對象。 在本例中,我創建了一個數據庫對象'Db'和一個可用於從數據庫中獲取數據的靜態類(現在只支持一種類型的數據對象):
class Db
{
public static IEnumerable<T> GetData<T>() {
if (typeof(T) == typeof(DataClass))
{
IEnumerable<DataClass> items = new DataClass[] {
new DataClass { IntValue1 = 101, IntValue2 = 102, StringValue1 = "1_1", StringValue2 = "1_2" },
new DataClass { IntValue1 = 201, IntValue2 = 202, StringValue1 = "2_1", StringValue2 = "2_2" },
new DataClass { IntValue1 = 301, IntValue2 = 302, StringValue1 = "3_1", StringValue2 = "3_2" },
new DataClass { IntValue1 = 401, IntValue2 = 402, StringValue1 = "4_1", StringValue2 = "4_2" },
new DataClass { IntValue1 = 501, IntValue2 = 502, StringValue1 = "5_1", StringValue2 = "5_2" }
};
return items as IEnumerable<T>;
}
// else
return Enumerable.Empty<T>();
}
}
並從數據庫中獲取數據:
static class DataList <TSource>
{
public static IEnumerable<TSource> GetList() {
return Db.GetData<TSource>();
}
}
正在使用的數據對象如下所示:
class DataClass
{
public int IntValue1 { get; set; }
public int IntValue2 { get; set; }
public string StringValue1 { get; set; }
public string StringValue2 { get; set; }
}
然后我希望能夠做到這樣的事情:
var items = DataList<DataClass>.GetList(x => new { Value1 = x.IntValue1 });
我首先看一下提供相同功能的'Select'Linq擴展方法的方法簽名,並在'DataList'類中創建了以下方法。
public static IEnumerable<TResult> GetList<TSource, TResult>(Func<TSource, TResult> selector)
{
IEnumerable<TSource> data = Db.GetData<TSource>();
return data.Select(selector);
}
讓我們忘記在這個例子中,我首先從數據庫中獲取完整的數據集,然后僅通過在匿名對象中選擇一個屬性來簡化數據集。
然而,事情是,如上所述的解決方案不起作用。 我在下面的行中收到編譯器錯誤:
var items = DataList<DataClass>.GetList(x => new { Value1 = x.IntValue1 });
錯誤是:
*錯誤2無法從用法推斷出方法'AnonymousTypeTest.DataList.GetList(System.Func)'的類型參數。 嘗試顯式指定類型參數。 O:\\ Ontwikkel \\ TryOuts \\ AnonymousTypeTest \\ AnonymousTypeTest \\ Form1.cs 21 25 AnonymousTypeTest *
在我看來,TSource和TResult都是眾所周知的。 同時指定類型參數也是有問題的,因為我不能將新的{Value1 = x.IntValue1}指定為類型參數。
有人知道上述解決方案的問題是什么,或者對於我在此描述的挑戰有更好的解決方案嗎?
GetList方法的定義存在問題。
public static IEnumerable<TResult> GetList<TSource, TResult>(Func<TSource, TResult> selector)
您正在添加與其中定義的TSource不同的其他類型參數TSource
static class DataList <TSource>
您只需要從GetList定義中刪除TSource。
public static IEnumerable<TResult> GetList<TResult>(Func<TSource, TResult> selector)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.