使用Linq拆分和分组

时间:2013-06-27 11:34:47

标签: c# .net linq

我已完成以下工作正常。

 public StandardReportsModel GetStandardReportsModel(string adUser, string adPassword, IPrincipal user)
 {

    var myItems = getMyItems().Where(myItem => !string.IsNullOrEmpty(myItem.Description));
    var categories = new List<string>();
    var myItems = new List<MyModel>();

    foreach (var myItem in myItems)
    {           
       var myIndex = myItem.Description.IndexOf('*');
       var category = myIndex != -1 ? myItem.Description.Substring(0, myIndex).ToUpper() : myItem.Description.ToUpper();   

       if (categories.IndexOf(category) == -1)
       {
          categories.Add(category);
       }              

       myItems.Add(getMyItem(myItem, category));
    }
    categories.Sort();      
    return new StandardModel { Categories = categories, MyItems = myItems };
 }

 private MyModel getMyItem(MyItem myItem, string category)
   {
     var categoryIdentifierIndex = myItem.Description.LastIndexOf(Delimiters.CategoryDescriptionDelimiter);
     var description = categoryIdentifierIndex != -1 ? myItem.Description.Substring(categoryIdentifierIndex + 1, (myItem.Description.Length - categoryIdentifierIndex + 1))) : myItem.Description;

     return new MyModel{ Name = myItem.Name, Description = myItem.Description, Category = category };
   }


 public class StandardModel
  {       
    public List<string> Categories { get; set; }
    public List<MyModel> MyItems { get; set; }        
  }

现在我正在尝试对Linq做同样的事情,我已经达到了以下。从获得的结果中我可以得到不同的类别并对其进行排序。有没有办法在单个查询中进行操作?

var result = myItems.Where(myItem => !string.IsNullOrEmpty(myItem.Description))                                    
             .Select(ci => new MyModel
               {
                 Name = ci.Name,
                 Category =  ci.Description.Split('*')[0],
                 Description = ci.Description.Split('*')[2]
               }).ToList();

我想要分类及其物品。可能我可能不得不在这里使用组。

请建议

1 个答案:

答案 0 :(得分:1)

 Dictionary<string, List<MyModel>> result = myItems
         .Where(myItem => !string.IsNullOrEmpty(myItem.Description))                                    
         .Select(ci => new MyModel
           {
             Name = ci.Name,
             Category =  ci.Description.Split('*')[0],
             Description = ci.Description.Split('*')[2]
           })
         .GroupBy(e => e.Category)
         .ToDictionary(e => e.Key, e => e.ToList());