问题描述
var schedules = new List<Item>{
new Item { Id=1, Name = "S" },
new Item { Id=2, Name = "P" },
new Item { Id=3, Name = "X" },
new Item { Id=4, Name = "X" },
new Item { Id=5, Name = "P" },
new Item { Id=6, Name = "P" },
new Item { Id=7, Name = "P" },
new Item { Id=8, Name = "S" }
};
我想在新列表中选择相同的值和相同的顺序,如下所示:
I want to select same values and same orders in a new list like this:
var groupedAndSelectedList = new List<List<Item>>{
new List<Item> {
new Item { Id=3, Name = "X" },
new Item { Id=4, Name = "X" },
},
new List<Item> {
new Item { Id=5, Name = "P" },
new Item { Id=6, Name = "P" },
new Item { Id=7, Name = "P" },
}
}
如果项目是单个项目,例如new Item { Id=3, Name = "A" }
,则不需要获取它.
If item is single like new Item { Id=3, Name = "A" }
I do not need to get it.
分组依据选择列表中的所有X或P元素.但是我想知道项目是在另一个项目之前还是之后.
Group by selects all X or P elements in list. But I want if items stands after or before another item.
使用linq可以吗?
推荐答案
此处要查找的是GroupWhile<T>
方法.
What you're looking for here is a GroupWhile<T>
method.
向用户 L.B 寻求解决方案.去给他的原始答案一个UpDoot https://stackoverflow.com/a/20469961/30155
Credit to user L.B for the solution. Go give his original answer an UpDoothttps://stackoverflow.com/a/20469961/30155
var schedules = new List<Item>{
new Item { Id=1, Name = "S" },
new Item { Id=2, Name = "P" },
new Item { Id=3, Name = "X" },
new Item { Id=4, Name = "X" },
new Item { Id=5, Name = "P" },
new Item { Id=6, Name = "P" },
new Item { Id=7, Name = "P" },
new Item { Id=8, Name = "S" }
};
var results = schedules
.GroupWhile((preceding, next) => preceding.Name == next.Name)
//Group items, while the next is equal to the preceding one
.Where(s => s.Count() > 1)
//Only include results where the generated sublist have more than 1 element.
.ToList();
foreach (var sublist in results)
{
foreach (Item i in sublist)
{
Console.WriteLine($"{i.Name} - {i.Id}");
}
Console.WriteLine("");
}
Console.ReadLine();
您可以像这样将实现作为扩展方法添加到所有IEnumerable<T>
中.
You can add the implementation as an Extension Method to all IEnumerable<T>
like so.
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> GroupWhile<T>(this IEnumerable<T> seq, Func<T, T, bool> condition)
{
T prev = seq.First();
List<T> list = new List<T>() { prev };
foreach (T item in seq.Skip(1))
{
if (condition(prev, item) == false)
{
yield return list;
list = new List<T>();
}
list.Add(item);
prev = item;
}
yield return list;
}
}
这篇关于如何查找与Linq组相同的连续值项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!