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

本文关键字:结构 映射 数据 何使用 linq | 更新日期: 2023-09-27 18:20:01

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

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

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

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

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

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

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

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