使用Linq进行拆分和分组
本文关键字:拆分 Linq 使用 | 更新日期: 2023-09-27 18:20:03
我已经完成了以下操作,运行良好。
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; }
}
现在我正试着和林克做同样的事情,我已经到达了下面。从得到的结果中,我可以区分类别并对其进行排序。有没有一种方法可以在单个查询中完成?
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();
我想要分类和他们的项目。也许我可能不得不使用这里的群组。
请建议
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());