Dominik Langer
Dominik Langer

Reputation: 11

Multiple same elements in the list, how to display only once, no duplicates?

My List contains multiple subjects, but some of them are the same. How to display all of them but without repetitions?

public class Subject
{
    public string SubjectName { get; set; }

    public Subject(string subjectName)
    {
        this.SubjectName = subjectName;
    }
}
List<Subject> listOfSubjects = new List<Subject>();
string subject = "";
Console.WriteLine("Enter the name of the subject");
subject = Console.ReadLine();
listofSubjects.Add(new Subject(subject));
string pastSubject = "";                   
foreach (Subject sub in listOfSubjects)
{
    if (sub.SubjectName != pastSubject)
    {
        Console.WriteLine(sub.SubjectName);
    }
    pastSubject = sub.SubjectName;
}

Upvotes: 1

Views: 302

Answers (3)

haldo
haldo

Reputation: 16711

If you use Linq then you can use GroupBy to get the distinct Subjects by name.

var distinctList = listOfSubjects
                     .GroupBy(s => s.SubjectName)    // group by names
                     .Select(g => g.First());        // take the first group

foreach (var subject in distinctList)
{
    Console.WriteLine(subject.SubjectName);
}

This method returns IEnumerable<Subject>, ie a collection of the actual Subject class.

I created a fiddle.

Upvotes: 1

Satyarth Misra
Satyarth Misra

Reputation: 11

One solution can be to build a IEqualityComparer<Subject> for the Subject class. Below is code for it.

public class SubjectComparer : IEqualityComparer<Subject>
{
    public bool Equals(Subject x, Subject y)
    {
        if (x == null && y == null)
        {
            return true;
        }
        else if (x == null || y == null)
        {
            return false;
        }
        else
        {
            return x.SubjectName == y.SubjectName;
        }
    }

    public int GetHashCode(Subject obj)
    {
        return obj.SubjectName.GetHashCode();
    }
}

Then just call the System.Linq Distinct function on it supplying the IEqualityComparer instance.

List<Subject> distinctSubjects = listOfSubjects.Distinct(new SubjectComparer()).ToList();

The resultant distinctSubjects list is Distinct.

Upvotes: 1

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112602

You can get distinct subject names with

var distinctSubjectNames = listOfSubjects
    .Select(s => s.SubjectName)
    .Distinct();
foreach (string subjectName in distinctSubjectNames) {
        Console.WriteLine(subjectName);
}

Upvotes: 0

Related Questions