2

I have a class as under

class WarningClass
    {
        public string SqlEyeWarning { get; set; }
        public string FileName { get; set; }
    }

It is populated as under

List<WarningClass> lstWarningClass1 = new List<WarningClass>();
lstWarningClass1.Add(new WarningClass { FileName = "a.sql", SqlEyeWarning = "SD001: order mismatch or it should be ON." });
lstWarningClass1.Add(new WarningClass { FileName = "a.sql", SqlEyeWarning = "SD001: order mismatch or it should be ON." });
lstWarningClass1.Add(new WarningClass { FileName = "c.sql", SqlEyeWarning = "SD009: Missing or order mismatch of Grant statement." });

As can be make out that there is a duplicate entry for the first and second record.

How to get unique entries.

Final output

FileName = "a.sql", SqlEyeWarning = "SD001: order mismatch or it should be ON." 
FileName = "c.sql", SqlEyeWarning = "SD009: Missing or order mismatch of Grant statement."

If I do lstWarningClass1.Distinct(), that does not work

cuongle
  • 74,024
  • 28
  • 151
  • 206
priyanka.sarkar
  • 25,766
  • 43
  • 127
  • 173

3 Answers3

3

Linq's Distinct() has the following in its description:

The default equality comparer, Default, is used to compare values of the types that implement the IEquatable generic interface. To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type.

Do the bolded part and Distinct() will work.

Patashu
  • 21,443
  • 3
  • 45
  • 53
1

You could use IEnumerable.GroupBy to group the objects in the list by the criteria that you care about. Then, you can select the first element of each group.

You can group by FileName like so:

lstWarningClass1.GroupBy(w => w.FileName).Select(g => g.First())

or by FileName and SqlEyeWarning like so:

lstWarningClass1.GroupBy(w => new {w.FileName, w.SqlEyeWarning}).Select(g => g.First())

Steven Wexler
  • 16,589
  • 8
  • 53
  • 80
1

You need to create a customize IEqualityComparer<T>:

public class CustomComparer : IEqualityComparer<WarningClass>
{
    public bool Equals(WarningClass x, WarningClass y)
    {
        return x.SqlEyeWarning.Equals(y.SqlEyeWarning)
               && x.FileName.Equals(y.FileName);
    }

    public int GetHashCode(WarningClass obj)
    {
        return obj.FileName.GetHashCode() 
            ^ obj.SqlEyeWarning.GetHashCode();
    }
}

Then call overloaded Distinct method with your customize comparer:

var result = lstWarningClass1.Distinct(new CustomComparer());
cuongle
  • 74,024
  • 28
  • 151
  • 206