我很困難..我需要採取一個對象的平面列表,作爲字符串的幾個字段數組數組(由哪個排序,哪個選擇)在運行時提供,並以某種方式生成一個LINQ查詢以返回JSON序列化的對象。動態建立一個使用字符串字段名稱的層次結構的linq查詢?
我已經建立了一個示例repro下面的設置。 OrderBy很簡單,我只是使用GetType()。GetProperty()來查找正確的屬性,並迭代orderby字段以菊花鏈.OrderBy調用。這一切都在GroupBy上分崩離析,因爲每一個都將結果包裝在IEnumerable>中。
有沒有一種很好的方法來做到這一點?我在網上找到的所有東西都有人訴諸舊的遞歸程序代碼。 LINQ必須有辦法做到這一點,但我迷路了。一切我嘗試甚至不會編譯,類型就不會匹配..
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic;
namespace linqtest2
{
class Program
{
static void Main(string[] args)
{
var products = new List<Product>
{
new Product("Food", "Fruit", "Apple"),
new Product("Food", "Fruit", "Banana"),
new Product("Food", "Fruit", "Orange"),
new Product("Food", "Vegetables", "Carrot"),
new Product("Food", "Vegetables", "Pea"),
new Product("Drink", "Soft Drink", "Orange Juice"),
new Product("Drink", "Soft Drink", "Lemonade"),
new Product("Drink", "Alcoholic", "Bitter"),
new Product("Drink", "Alcoholic", "Lager"),
new Product("Drink", "Alcoholic", "Vodka")
};
string[] select = new[] { "Category", "Name" };
string[] orderBy = new[] { "Name", "Category" };
string[] groupBy = new[] { "Category", "Subcategory" };
}
}
public class Product
{
public string Name { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
public Product(string category, string subcategory, string name)
{
Category = category;
Subcategory = subcategory;
Name = name;
}
}
}
我該如何動態執行此操作?我需要以某種方式迭代陣列,然後一次添加這些。 – XeroxDucati
@XeroxDucati我更新了答案。 – LawfulHacker