我有一个序列。例如:
new [] { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 }现在我必须在不改变整体顺序的情况下删除重复的值。对于上面的序列:
new [] { 10, 1, 5, 25, 45, 40, 100, 1, 2, 3 }如何使用LINQ做到这一点?
发布于 2012-05-26 20:15:35
使用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;
        }
    }
}你可以这样使用它:
int[] packed = myArray.PackGroups().ToArray();这个问题并不清楚在1,1,2,3,3,1的情况下应该返回什么。大多数给出的答案返回1,2,3,而我的答案返回1,2,3,1。
https://stackoverflow.com/questions/10766072
复制相似问题