0

I made myclass and put it in a list.

In this list, if there is an 'MyClass' with the same address, I want to leave only one 'MyClass' with the smallest signal.

For example,

class MyClass
{
    public int Id { get; set; }
    public int signal { get; set; }
    public int Address { get; set; }
}

static List<MyClass> myClasses = new List<MyClass>();

static void Main(string[] args)
{
    MyClass myClass = new MyClass();
    myClass.Id = 1;
    myClass.signal = 2;
    myClass.Address = 1234;
    myClasses.Add(myClass);

    myClass.Id = 1;
    myClass.signal = 4;
    myClass.Address = 5678;
    myClasses.Add(myClass);

    myClass.Id = 2;
    myClass.signal = 3;
    myClass.Address = 1234;
    myClasses.Add(myClass);

    myClass.Id = 2;
    myClass.signal = 3;
    myClass.Address = 5678;
    myClasses.Add(myClass);
}

In the above situation I would like to leave something like below in myclasses.

myClass.Id = 1;
myClass.signal = 2;
myClass.Address = 1234;

myClass.Id = 2;
myClass.signal = 3;
myClass.Address = 5678;

I think we can solve it with Linq, what should I do?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
playground
  • 75
  • 6

1 Answers1

2

To begin with, your sample code in OP would result in same item being copied over again and again as you are referring to same object myClass. This would result in the following in your List.

enter image description here

Assuming, that was a mistake while reproducing the issue, you could recreate your intended List as following.

var myClasses = new List<MyClass>
{
        new MyClass
        {
            Id=1,
            signal=2,
            Address = 1234
        },
        new MyClass
        {
            Id=1,
            signal=4,
            Address = 5678
        },
        new MyClass
        {
            Id=2,
            signal=3,
            Address = 1234
        },
        new MyClass
        {
            Id=2,
            signal=3,
            Address = 5678
        },
};

Now assuming the criteria for duplicate is MyClass.Id, You could now Group the List with Id and then sort each sub-group with signal, picking up the smallest.

myClasses.GroupBy(x=>x.Id).Select(x=>x.OrderBy(x=>x.signal).First());

This would produce the desired result as

enter image description here

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51