如何使用linq将数据映射到类结构?

时间:2015-11-01 14:19:22

标签: c# linq class mapping

我有一些用逗号分隔的原始数据,如:

name value  Image              catID   ID

Blue, era , Colors/col_image       ,37  ,  1

pink, aka, Colors/col_image        ,37  ,  2

我准备了一个类结构,如:

public class DailyStuffs
{
    public string StuffName { get; set; }
    public string ConvertedName { get; set; }
    public string StuffImage { get; set; }
    public int CategoryId { get; set; }
}

 public class StuffType
{
   public string Category { get; set; }       
   public List<DailyStuffs> dailyStuffs;
}

我想根据类别(颜色,鸟类等)对项目进行分组。我尝试使用以下代码:

 List<StuffType> stuff = (from line in lines
                                      let data = line.Split(',').ToList()
                                      select new StuffType
                                      {
                                          Category = DefineRange(Convert.ToInt16(data[4])),
                                          dailyStuffs = (from dat in data select new DailyStuffs { StuffName = data[1] }).ToList()
                                      }).ToList();

并且DefineRange返回一个字符串值:

private string DefineRange(int value)
   {
       if (value >= 1 && value <= 10)
       {
           return "Colors";
       }}

我收到一个错误的列表,其中包含类别作为每个项目的一部分。

有什么建议吗?我该怎么办呢?

2 个答案:

答案 0 :(得分:0)

假设我正确理解了原始数据和类属性之间的映射,那么你应该这样做:

var result = list.Select(str =>
        str
            .Split(',')
            .Select(v => v.Trim()).ToArray())
    .Select(x =>
        new
        {
            Name = x[0],
            Value = x[1],
            Image = x[2],
            CatId = Convert.ToInt32(x[3]),
            Id = Convert.ToInt32(x[4])
        })
    .GroupBy(x => x.CatId)
    .Select(x => new StuffType
    {
        Category = DefineRange(x.Key),
        dailyStuffs = x.Select(y => new DailyStuffs
        {
            CategoryId = x.Key, //Maybe instead here you want to put the Id?
            ConvertedName = y.Value, //I am mapping from Value to ConvertedName. Is this correct?
            StuffImage = y.Image,
            StuffName = y.Name
        }).ToList()
    }).ToList();

答案 1 :(得分:0)

您的代码中似乎有一些错误。类别列为data[3],名称列为data[0]。您可以使用最接近您设计的LINQ:

var stuff = (from line in lines
             let data = line.Split(',').ToList()
             group data by data[3] into c
             select new StuffType {
                 Category = DefineRange(Convert.ToInt32(c.Key)),
                 dailyStuffs = (from s in c
                                select new DailyStuffs {
                                    StuffName = s[0],
                                    ConvertedName = s[1],
                                    StuffImage = s[2],
                                    CategoryId = Convert.ToInt32(s[3])
                                }).ToList()
             }).ToList();

当然,您必须修复DefineRange()功能才能使用catID列。这是一个fiddle。我输入了更多数据进行测试。