static void Main(string[] args) { var cats = new[] { new Categories { Count = "5", ValueCode = "cat1/sc1", DisplayName = "Category1/SubCategory1" }, new Categories { Count = "4", ValueCode = "cat1/sc2", DisplayName = "Category1/SubCategory2" }, new Categories { Count = "5", ValueCode = "cat2/sc1", DisplayName = "Category2/Subcategory1" }, new Categories { Count = "23", ValueCode = "cat2/sc2", DisplayName = "Category2/Subcategory2" } }; var categories = cats.Select(x => x.DisplayName.Split('/')[0]).Distinct(); var list = new List<JobCateogries>(); foreach (var category in categories) { var a = new JobCateogries { ValueCode = cats.Where(x => x.DisplayName.Split('/')[0] == category) .Select(x => x.ValueCode.Split('/')[0]).FirstOrDefault(), DisplayName = category, SubCategories = cats.Where(x => x.DisplayName.Split('/')[0] == category) .Select(x => new JobCateogries { SubCategories = new List<JobCateogries>(), Count = x.Count, DisplayName = x.DisplayName.Split('/')[1], ValueCode = x.ValueCode.Split('/')[1] }).ToList(), }; a.Count = a.SubCategories.Select(x => int.Parse(x.Count)).Sum().ToString(); list.Add(a); } list.ForEach(x => Print(x)); Console.ReadKey(); } public static void Print(JobCateogries category, int indent = 0) { var prefix = string.Empty.PadLeft(indent); Console.WriteLine(prefix + category.DisplayName); Console.WriteLine(prefix + category.ValueCode); Console.WriteLine(prefix + category.Count); category.SubCategories.ForEach(x => Print(x, indent + 4)); } 这篇关于Linq拆分类的属性,并将其分配给另一个自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-09 21:15