[英]How to group the same values in a sequence with LINQ?
I have a sequence. 我有一个序列。 For example:
例如:
new [] { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 }
Now I have to remove duplicated values without changing the overall order. 现在我必须删除重复的值而不更改整体顺序。 For the sequence above:
对于上面的序列:
new [] { 10, 1, 5, 25, 45, 40, 100, 1, 2, 3 }
How to do this with LINQ? 如何使用LINQ执行此操作?
var list = new List<int> { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };
var result = list.Where((item, index) => index == 0 || list[index - 1] != item);
var list = new List<int> { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };
List<int> result = list.Where((x, index) =>
{
return index == 0 || x != list.ElementAt(index - 1) ? true : false;
}).ToList();
This returns what you want. 这会返回您想要的内容。 Hope it helped.
希望它有所帮助。
Did you try
Distinct
?
你尝试过
Distinct
吗?
var list = new [] { 10, 20, 20, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 }; list = list.Distinct();
Edit : Since you apparently only want to group items with the same values when consecutive , you could use the following: 编辑 :由于您显然只想在连续时对具有相同值的项目进行分组,因此您可以使用以下内容:
var list = new[] { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };
List<int> result = new List<int>();
foreach (int item in list)
if (result.Any() == false || result.Last() != item)
result.Add(item);
You can use Contains and preserve order 您可以使用包含并保留订单
List<int> newList = new List<int>();
foreach (int n in numbers)
if (newList.Count == 0 || newList.Last() != n)
newList.Add(n);
var newArray = newList.ToArray();
OUTPUT: OUTPUT:
10, 1, 5, 25, 45, 40, 100, 1, 2, 3
10,1,5,25,45,40,100,1,2,3
It may be technically possible (though I don't think you can with a one-liner) to solve this with LINQ, but I think it's more elegant to write it yourself. 在技术上可能(虽然我不认为你可以使用单行)用LINQ来解决这个问题,但我认为自己编写它会更优雅。
public static class ExtensionMethods
{
public static IEnumerable<T> PackGroups<T>(this IEnumerable<T> e)
{
T lastItem = default(T);
bool first = true;
foreach(T item in e)
{
if (!first && EqualityComparer<T>.Default.Equals(item, lastItem))
continue;
first = false;
yield return item;
lastItem = item;
}
}
}
You can use it like this: 你可以像这样使用它:
int[] packed = myArray.PackGroups().ToArray();
It's unclear from the question what should be returned in the case of 1,1,2,3,3,1
. 从问题中不清楚在
1,1,2,3,3,1
的情况下应该返回什么。 Most answers given return 1,2,3
, whereas mine returns 1,2,3,1
. 给出的大多数答案返回
1,2,3
,而我的返回1,2,3,1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.