シーケンスがあります。例えば:
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でこれを行う方法は?
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();
これにより、必要なものが返されます。お役に立てば幸いです。
やってみましたDistinct
か?
var list = new [] { 10, 20, 20, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };
list = list.Distinct();
編集:明らかに、連続しているときに同じ値のアイテムのみをグループ化したいので、次を使用できます。
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);
含むを使用して順序を保持できます
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();
出力:
10、1、5、25、45、40、100、1、2、3
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
。