分组依据的属性类型

时间:2018-11-06 20:18:06

标签: c# .net linq

我有一个工作组,但我无法弄清楚我的视图模型需要保留结果的属性类型。

public class Person
{
    public string FirstName { get; set; }
    public string Car { get; set; }
}   

结果

results[0] FirstName = "Bob" Cars =  {"Mercedes", "bmw"}
results[1] FirstName = "David" Cars =  {"Porsche", "Vauxhall"}


public class DataViewModel
{
    // Need a prop to hold the value of result
}

public ActionResult Index()
{
    var result = from p in persons
    group p.car by p.FirstName into g
    select new { FirstName = g.Key, Cars = g.ToList() };

    var model = new DataViewModel();
    model.?? = result; 
}

1 个答案:

答案 0 :(得分:1)

我已经通过使用一个复杂的对象来保存值来解决了这个问题

public class ComplexObject
{
      public string FirstName {get; set; }
      public List<string> Cars {get; set; }
}

var result = from p in persons
    group p.car by p.FirstName into g
    select new ComplexObject { FirstName = g.Key, Cars = g.ToList() };