CSharp - Use Distinct Operator Without an Equality Comparer

Description

Use Distinct Operator Without an Equality Comparer

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Data;

class Program//from  w  ww  . j  av  a2s. c o m
{
    static void Main(string[] args)
    {
        Student[] students = {
          new Student { Id = 1, Name = "Joe Ruby" },
          new Student { Id = 6, Name = "Oracle Express" },
          new Student { Id = 19, Name = "Bob Json" },
          new Student { Id = 45, Name = "CSS Java" },
          new Student { Id = 1, Name = "Joe Ruby" },
          new Student { Id = 12, Name = "Bob Javascript" },
          new Student { Id = 17, Name = "Apache Python" },
          new Student { Id = 32, Name = "Django SQL" }
        };
        DataTable dt = GetDataTable(students);

        Console.WriteLine("{0}Before calling Distinct(){0}",
          System.Environment.NewLine);

        OutputDataTableHeader(dt, 15);

        foreach (DataRow dataRow in dt.Rows)
        {
            Console.WriteLine("{0,-15}{1,-15}",
              dataRow.Field<int>(0),
              dataRow.Field<string>(1));
        }

        IEnumerable<DataRow> distinct =
          dt.AsEnumerable().Distinct();

        Console.WriteLine("{0}After calling Distinct(){0}",
          System.Environment.NewLine);

        OutputDataTableHeader(dt, 15);

        foreach (DataRow dataRow in distinct)
        {
            Console.WriteLine("{0,-15}{1,-15}",
              dataRow.Field<int>(0),
              dataRow.Field<string>(1));
        }
    }
    static void OutputDataTableHeader(DataTable dt, int columnWidth)
    {
        string format = string.Format("{0}0,-{1}{2}", "{", columnWidth, "}");

        //  Display the column headings.
        foreach (DataColumn column in dt.Columns)
        {
            Console.Write(format, column.ColumnName);
        }
        Console.WriteLine();
        foreach (DataColumn column in dt.Columns)
        {
            for (int i = 0; i < columnWidth; i++)
            {
                Console.Write("=");
            }
        }
        Console.WriteLine();
    }
    static DataTable GetDataTable(Student[] students)
    {
        DataTable table = new DataTable();

        table.Columns.Add("Id", typeof(Int32));
        table.Columns.Add("Name", typeof(string));

        foreach (Student student in students)
        {
            table.Rows.Add(student.Id, student.Name);
        }

        return (table);
    }
}

class Student
{
    public int Id;
    public string Name;
}

Result

Related Topic