Eliminate consecutive duplicates of list elements

前端 未结 11 1563
南笙
南笙 2020-12-03 02:31

Is there a \"nice\" way to eliminate consecutive duplicates of list elements?

Example:

[\"red\"; \"red\"; \"blue\"; \"green         


        
11条回答
  •  无人及你
    2020-12-03 03:01

    Taking @Simon Bartlett's clean approach and improving upon it, you could also perform this generically.

    public static IEnumerable UniqueInOrder(IEnumerable iterable)
    {
        var returnList = new List();
    
        foreach (var item in iterable)
        {
            if (returnList.Count == 0 || !returnList.Last().Equals(item))
                returnList.Add(item);
        }
    
        return returnList;
    }
    

提交回复
热议问题