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

How to map data to class structure using linq?

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

name value  Image              catID   ID

Blue, era , Colors/col_image       ,37  ,  1

pink, aka, Colors/col_image        ,37  ,  2

我准备了一个 class 结构,例如:

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";
       }}

我得到一个错误的列表,每个项目都有类别。

大家有什么建议吗?我该如何处理?

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

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();

您的代码似乎有一些错误。类别列为 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。我输入了更多数据进行测试。