我有以下课程:
我有类似这个类的列表:
我想通过已批准从列表组中获取项目,但我希望分组对象按此顺序排列:
提前致谢
答案 0 :(得分:0)
看起来你需要使用TakeWhile方法
http://msdn.microsoft.com/ru-ru/library/bb534804(v=vs.95).aspx
我在LINQ方面不是很好但是这段代码应该可行。这个原则不仅可以扩展到布尔值,还可以扩展到支持IEqualityComparer
的任何类型var list = new List<Test>();
list.Add(new Test(1, true, true));
list.Add(new Test(2, true, true));
list.Add(new Test(3, true, true));
list.Add(new Test(4, true, false));
list.Add(new Test(5, true, false));
list.Add(new Test(6, true, false));
list.Add(new Test(7, true, true));
list.Add(new Test(8, true, true));
list.Add(new Test(9, true, false));
var listTemp = list;
var result = new List<Tuple<bool, List<Test>>>();
while (listTemp.Count > 0)
{
var approved = listTemp[0].Approved;
var tuple = new Tuple<bool, List<Test>>(approved, listTemp.TakeWhile(x => approved == x.Approved).ToList());
result.Add(tuple);
listTemp = listTemp.SkipWhile(x => approved == x.Approved).ToList();
}
答案 1 :(得分:0)
这应该有效:
var data = list.OrderBy(x => x.Id);
bool approved = data.First().Approved;
var groups = new List<Tuple<bool, List<Foo>>>();
var all = groups.SelectMany(x => x.Item2);
while (all.Count() != list.Count())
{
groups.Add(
Tuple.Create(
approved
, list.Skip(all.Count())
.TakeWhile(x => x.Approved == approved)
.ToList()));
approved = !approved;
}
foreach (var grp in groups)
{
Console.Write("Next block: {0} with {1} elements", grp.Item1, grp.Item2.Count);
}
这是你的班级:
class Foo
{
public int Id { get; set; }
public bool Active { get; set; }
public DateTime datetime { get; set; }
public bool Approved { get; set; }
}
和样本数据:
var list = new List<Foo>();
list.Add(new Foo() { Id = 1, Active = true, Approved = true });
list.Add(new Foo() { Id = 2, Active = true, Approved = true });
list.Add(new Foo() { Id = 3, Active = true, Approved = true });
list.Add(new Foo() { Id = 4, Active = true, Approved = false });
list.Add(new Foo() { Id = 5, Active = true, Approved = false });
list.Add(new Foo() { Id = 6, Active = true, Approved = false });
list.Add(new Foo() { Id = 7, Active = true, Approved = true });
list.Add(new Foo() { Id = 8, Active = true, Approved = true });
list.Add(new Foo() { Id = 9, Active = true, Approved = false });