Home > database >  Selecting the first record from a collection with Duplicate column values C#
Selecting the first record from a collection with Duplicate column values C#

Time:12-16

I have a list of Records.

public class Record 
{
 public int Id{get;set;}
 public string Name {get;set;}
 public string Description{get;set;}
}

List<Record> records = 
{
  1, "A","Desc1",
  2, "A","Desc2",
  3, "B","Desc3",
  4, "B","Desc4",
  5, "C","Desc5"
}

I need to check the Name and if its same , pick the first record . So , I need the output as :

 List<Record> records = 
    {
      1, "A","Desc1",
      3, "B","Desc3",
      5, "C","Desc5"
    }

I tried to group , but I dont need all the columns in grouping list.

CodePudding user response:

you can use Linq with a group by name and take the first group element:

var cleaned = from r in records
              group r by r.Name into grp
              select grp.First();

CodePudding user response:

I assume you want a complete list, and not just a single item.

I would suggest to use a HashSet which does not allow any duplicates. And if it is a duplicate or not, you need to control through overriding the Equals and GetHashCode functions in the class like this:

public class Record
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    
    public override bool Equals(object obj)
    {
        Record other = obj as Record;

        return !Object.ReferenceEquals(null, other)
            && String.Equals(this.Name, other.Name);
    }

    public override int GetHashCode()
    {
        int hash = 13;
        hash = (hash * 7)   this.Name.GetHashCode();
        return hash;
    }
}

The Equals and GetHashCode functions MUST only work based on the Name (because this is determining your uniqueness in this case).

Then you can simply create a Hashset from your list

HashSet<Record> uniqueRecords = new HashSet<Record>(records);

If you really need a list, then you can just convert back to a list.

CodePudding user response:

One attempt could be to sort the list of records by description and after that filter by distinct names:

var filteredRecords = records.OrderBy(x => x.Description).DistinctBy(x => x.Name);
  • Related