質問

プロパティ(Id、Name、Code、Price)を持つクラス Items があります。

Items のリストには、重複したアイテムが表示されます。

例:

1         Item1       IT00001        $100
2         Item2       IT00002        $200
3         Item3       IT00003        $150
1         Item1       IT00001        $100
3         Item3       IT00003        $150

linqを使用してリスト内の重複を削除する方法?

役に立ちましたか?

解決

var distinctItems = items.Distinct();

一部のプロパティのみで一致させるには、カスタム等値比較子を作成します。例:

class DistinctItemComparer : IEqualityComparer<Item> {

    public bool Equals(Item x, Item y) {
        return x.Id == y.Id &&
            x.Name == y.Name &&
            x.Code == y.Code &&
            x.Price == y.Price;
    }

    public int GetHashCode(Item obj) {
        return obj.Id.GetHashCode() ^
            obj.Name.GetHashCode() ^
            obj.Code.GetHashCode() ^
            obj.Price.GetHashCode();
    }
}

次のように使用します:

var distinctItems = items.Distinct(new DistinctItemComparer());

他のヒント

var distinctItems = items.GroupBy(x => x.Id).Select(y => y.First());

Distinctクエリを無効にしているものがある場合は、をご覧ください。 MoreLinq を使用し、DistinctBy演算子を使用して、IDによって個別のオブジェクトを選択します。

var distinct = items.DistinctBy( i => i.Id );

これが、私がLinqでグループ化する方法です。役に立てば幸いです。

var query = collection.GroupBy(x => x.title).Select(y => y.FirstOrDefault());

Distinct()を使用しますが、デフォルトの等値比較器を使用して値を比較するため、それ以上のものが必要な場合は独自の比較器を実装する必要があります。

http://msdn.microsoft.com/en-us/をご覧ください。 library / bb348436.aspx の例。

リスト内の重複するアイテムを削除するには、3つのオプションがあります:

  1. カスタム等価比較器を使用してから、 Distinct(new DistinctItemComparer()) @Christian Hayter 言及。
  2. GroupBy を使用しますが、 GroupBy ではすべての列でグループ化する必要があることに注意してください。常に重複するアイテムが削除されるわけではありません。たとえば、次の例を考えてみましょう。

    List<Item> a = new List<Item>
    {
        new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
        new Item {Id = 2, Name = "Item2", Code = "IT00002", Price = 200},
        new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
        new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
        new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
        new Item {Id = 3, Name = "Item3", Code = "IT00004", Price = 250}
    };
    var distinctItems = a.GroupBy(x => x.Id).Select(y => y.First());
    

    このグループ化の結果は次のようになります。

    {Id = 1, Name = "Item1", Code = "IT00001", Price = 100}
    {Id = 2, Name = "Item2", Code = "IT00002", Price = 200}
    {Id = 3, Name = "Item3", Code = "IT00003", Price = 150}
    

    {Id = 3、Name =&quot; Item3&quot;、Code =&quot; IT00004&quot;、Price = 250} は重複と見なされるため、どちらが間違っています。したがって、正しいクエリは次のようになります。

    var distinctItems = a.GroupBy(c => new { c.Id , c.Name , c.Code , c.Price})
                         .Select(c => c.First()).ToList();
    

    3。アイテムクラスで Equal および GetHashCode をオーバーライドします:

    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public int Price { get; set; }
    
        public override bool Equals(object obj)
        {
            if (!(obj is Item))
                return false;
            Item p = (Item)obj;
            return (p.Id == Id && p.Name == Name && p.Code == Code && p.Price == Price);
        }
        public override int GetHashCode()
        {
            return String.Format("{0}|{1}|{2}|{3}", Id, Name, Code, Price).GetHashCode();
        }
    }
    

    その後、次のように使用できます:

    var distinctItems = a.Distinct();
    

ユニバーサル拡張メソッド:

public static class EnumerableExtensions
{
    public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> enumerable, Func<T, TKey> keySelector)
    {
        return enumerable.GroupBy(keySelector).Select(grp => grp.First());
    }
}

使用例:

var lstDst = lst.DistinctBy(item => item.Key);
List<Employee> employees = new List<Employee>()
{
    new Employee{Id =1,Name="AAAAA"}
    , new Employee{Id =2,Name="BBBBB"}
    , new Employee{Id =3,Name="AAAAA"}
    , new Employee{Id =4,Name="CCCCC"}
    , new Employee{Id =5,Name="AAAAA"}
};

List<Employee> duplicateEmployees = employees.Except(employees.GroupBy(i => i.Name)
                                             .Select(ss => ss.FirstOrDefault()))
                                            .ToList();

この拡張メソッドを試してください。これが役立つことを願っています。

public static class DistinctHelper
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        var identifiedKeys = new HashSet<TKey>();
        return source.Where(element => identifiedKeys.Add(keySelector(element)));
    }
}

使用法:

var outputList = sourceList.DistinctBy(x => x.TargetProperty);

IEqualityComparerを書きたくない場合は、次のようなものを試すことができます。

 class Program
{

    private static void Main(string[] args)
    {

        var items = new List<Item>();
        items.Add(new Item {Id = 1, Name = "Item1"});
        items.Add(new Item {Id = 2, Name = "Item2"});
        items.Add(new Item {Id = 3, Name = "Item3"});

        //Duplicate item
        items.Add(new Item {Id = 4, Name = "Item4"});
        //Duplicate item
        items.Add(new Item {Id = 2, Name = "Item2"});

        items.Add(new Item {Id = 3, Name = "Item3"});

        var res = items.Select(i => new {i.Id, i.Name})
            .Distinct().Select(x => new Item {Id = x.Id, Name = x.Name}).ToList();

        // now res contains distinct records
    }



}


public class Item
{
    public int Id { get; set; }

    public string Name { get; set; }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top