【发布时间】:2014-05-13 01:01:08
【问题描述】:
我很难过.. 我需要在运行时提供一个对象列表、几个字段名称数组作为字符串(分组依据、排序依据和选择),并且以某种方式生成一个 LINQ 查询以返回一个用于 JSON 序列化的对象。
我在设置下方构建了一个示例重现。 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;
}
}
}
【问题讨论】:
标签: c# linq linq-to-objects