4

シーケンスがあります。例えば:

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でこれを行う方法は?

4

5 に答える 5

3
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);
于 2012-05-26T14:00:00.370 に答える
3
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();

これにより、必要なものが返されます。お役に立てば幸いです。

于 2012-05-26T14:00:11.730 に答える
1

やってみました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);
于 2012-05-26T12:09:49.360 に答える
1

含むを使用して順序を保持できます

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

于 2012-05-26T12:10:29.830 に答える
1

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

于 2012-05-26T12:15:34.633 に答える