簡體   English   中英

將Linq表達式傳遞給函數

[英]Pass Linq Expression to a function

我想將類的屬性列表傳遞給函數。 在基於屬性列表的函數中,我將生成一個查詢。 與Linq Select方法中的功能完全相同。 在這里,我將為Ingress數據庫實現此功能。

舉個例子,

在前端,我想選擇一個,

我的實體類是這樣的

public class Customer
{
    [System.Data.Linq.Mapping.ColumnAttribute(Name="Id",IsPrimaryKey=true)]
    public string Id { get; set; }

    [System.Data.Linq.Mapping.ColumnAttribute(Name = "Name")]
    public string Name { get; set; }

    [System.Data.Linq.Mapping.ColumnAttribute(Name = "Address")]
    public string Address { get; set; }

    [System.Data.Linq.Mapping.ColumnAttribute(Name = "Email")]
    public string Email { get; set; }

    [System.Data.Linq.Mapping.ColumnAttribute(Name = "Mobile")]
    public string Mobile { get; set; }
}

我想這樣調用Select函數,

var result = dataAccessService.Select<Customer>(C=>C.Name,C.Address);

然后,使用結果我可以獲取Name和Address屬性的值。

我認為我的Select函數應該看起來像這樣,

(*我認為這應該使用Linq Expression完成。但是我不確定輸入參數和返回類型是什么。*)

Class DataAccessService
{
   // I'm not sure about this return type and input types, generic types.
   public TResult Select<TSource,TResult>(Expression<Func<TSource,TResult>> selector)
   {
        // Here I wanna Iterate through the property list, which is passed from the caller.
        // Here using the property list, 
        // I can get the ColumnAttribute name value and I can generate a select query.
   }
}

嘗試創建類似Linq的功能。 但是我不是Linq Expressions的專家。

麻省理工學院有一個名為DbLinq的項目,但這是一個很大的項目,我仍然無法從中獲得任何幫助。

有人可以幫我開始這個問題嗎,或者可以給我鏈接一些有用的資源來了解這一點。

您想要做的是創建一個由名稱和地址組成的新匿名類型。 這可以通過長格式的linq輕松實現(由於缺乏更好的解釋,我用了這個術語。)這是Microsoft的示例,下面提供了鏈接:

public void Linq11() 
{ 
    List<Product> products = GetProductList(); 

    var productInfos = 
        from p in products 
        select new { p.ProductName, p.Category, Price = p.UnitPrice }; 

    Console.WriteLine("Product Info:"); 
    foreach (var productInfo in productInfos) 
    { 
        Console.WriteLine("{0} is in the category {1} and costs {2} per unit.", productInfo.ProductName, productInfo.Category, productInfo.Price); 
    } 
}

詳細信息: Linq選擇樣品

更新:那么您是否正在嘗試做類似的事情?

   var result = dataAccessService.Select<Customer>(c => c.Name, c => c.Address);

public object[] Select<TSource>(params Expression<Func<TSource, object>>[] selectors)
   {
       var toReturn = new object[selectors.Count()];

       foreach (var s in selectors)
       {
           var func = s.Compile();
           //TODO: If you implement Select a proper extension method, you can easily get the source
           toReturn[i] = func(TSource);
       }
        return toReturn;
   }

我不明白為什么您要嘗試將Select實現為DataAccessService的功能? 試圖將其創建為擴展方法嗎? 如果這不是您的意思,則需要重新表達您的疑問,並如一位評論者所建議的,告訴我們您不需要什么,我們希望如何設計它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM