假设我有一份期刊清单:
class Journal { public int ID; public string Name; }
var objListJournals = new List<Journal>
{
new Journal{ID = 1, Name = "Tom"}, new Journal{ID = 2, Name = "Jerry"},
new Journal{ID = 1, Name = "Brad"}, new Journal{ID = 3, Name = "Frog"},
new Journal{ID = 1, Name = "Alex"}, new Journal{ID = 2, Name = "Don"}
};
现在我想要的是,这个列表将根据ID明智分割。所以它应该是这样的:
list 1: {ID=1, Name="Tom"},{ID=1, Name="Brad"}, {ID=1, Name="Alex"}
list 2: {ID=2, Name="Jerry"}, {ID=2, Name="Don"}
list 3: {ID=3, Name="Frog"}
以便我可以将它们添加到新列表中 -
List<Journal> objNewList = new List<List<Journal>>();
objNewList.Add(list1);
objNewList.Add(list2);
..........
怎么办?
答案 0 :(得分:2)
假设您的问题包含有效代码:
class Journal { public int ID; public string Name; }
var journals = new List<Journal>
{
new Journal{ID = 1, Name = "Tom"}, new Journal{ID = 2, Name = "Jerry"},
new Journal{ID = 1, Name = "Brad"}, new Journal{ID = 3, Name = "Frog"},
new Journal{ID = 1, Name = "Alex"}, new Journal{ID = 2, Name = "Don"}
};
实际上编译为列表,您可以使用Linq groupby将实例中的一个成员分组到组中。
这会为您提供一个IEnumerable<IGrouping<int,Journal>>
,您可以使用Select
到IEnumerable<List<Journal>>
来展平 - 如果您确实需要List<List<Journal>>
,请致电ToList()
在那:
using System.Linq;
using System;
using System.Collections.Generic;
public class Program
{
class Journal { public int ID; public string Name; }
static void T()
{
var journals = new List<Journal>
{
new Journal{ID = 1, Name = "Tom"}, new Journal{ID = 2, Name = "Jerry"},
new Journal{ID = 1, Name = "Brad"}, new Journal{ID = 3, Name = "Frog"},
new Journal{ID = 1, Name = "Alex"}, new Journal{ID = 2, Name = "Don"}};
var listById = journals
.GroupBy(j => j.ID) // grouping into IEnumerable<IGrouping<int,Journal>>
.Select(i => i.ToList()); // flattening to IEnumerable<List<Journal>
foreach(var list in listById)
Console.WriteLine(string.Join(",",
list.Select(l => string.Format("ID: {0} - NAME: {1}", l.ID , l.Name))));
}
public static void Main()
{
T();
}
}
输出:
ID: 1 - NAME: Tom,ID: 1 - NAME: Brad,ID: 1 - NAME: Alex
ID: 2 - NAME: Jerry,ID: 2 - NAME: Don
ID: 3 - NAME: Frog
答案 1 :(得分:0)
在没有列表清单的情况下解决此问题的另一种方法:
var journals = new List<Journal>
{
new Journal {ID = 1, Name = "Tom"},
new Journal {ID = 2, Name = "Jerry"},
new Journal {ID = 1, Name = "Brad"},
new Journal {ID = 3, Name = "Frog"},
new Journal {ID = 1, Name = "Alex"},
new Journal {ID = 2, Name = "Don"}
};
var res =
journals.GroupBy(x => x.ID, y => y.Name)
.Select(x => new {ID = $"ID: {x.Key}" , Names = $"NAMES: {string.Join(", ", x)}"})
.ToList();
foreach (var item in res)
{
Console.WriteLine($"{item.ID} {item.Names}");
}
答案 2 :(得分:-2)
您可以使用GroupBy
;
var result = objJournalList.GroupBy(x => x.Id).Select(x => x.Select(k => k));