Csharp/CSharp Tutorial/LINQ/Distinct

Материал из .Net Framework эксперт
Версия от 12:18, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Distinct Operator

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"Grant", "Harding", "Harrison", "Hayes", "Hoover", "Jackson"};
        Console.WriteLine("presidents count:  " + presidents.Count());
        IEnumerable<string> presidentsWithDupes = presidents.Concat(presidents);
        Console.WriteLine("presidentsWithDupes count:  " + presidentsWithDupes.Count());
        IEnumerable<string> presidentsDistinct = presidentsWithDupes.Distinct();
        Console.WriteLine("presidentsDistinct count:  " + presidentsDistinct.Count());
    }
}

Get all Make and don"t show duplicates

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using System.Linq;
    class Car
    {
        public string PetName;
        public string Color;
        public int Speed;
        public string Make;
        
        public override string ToString()
        {
            return string.Format("Make={0}, Color={1}, Speed={2}, PetName={3}",Make, Color, Speed, PetName);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Car[] myCars = new []{
                new Car{ PetName = "A", Color = "Silver", Speed = 100, Make = "BMW"},
                new Car{ PetName = "B", Color = "Black", Speed = 55, Make = "VW"},
                new Car{ PetName = "C", Color = "White", Speed = 43, Make = "Ford"}
            };
        
            var makes = from c in myCars select c.Make;
            foreach (var m in makes.Distinct<string>())
            {
                Console.WriteLine("Make: {0}", m);
            }
        
        
        }
    }

Get Distinct departments

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Tree<TreeNode> : IEnumerable<TreeNode> where TreeNode : IComparable<TreeNode> {
    public Tree(TreeNode nodeValue) {
        this.NodeData = nodeValue;
        this.LeftTree = null;
        this.RightTree = null;
    }
    public void Insert(TreeNode newItem) {
        TreeNode currentNodeValue = this.NodeData;
        if (currentNodeValue.rupareTo(newItem) > 0) {
            if (this.LeftTree == null) {
                this.LeftTree = new Tree<TreeNode>(newItem);
            } else {
                this.LeftTree.Insert(newItem);
            }
        } else {
            if (this.RightTree == null) {
                this.RightTree = new Tree<TreeNode>(newItem);
            } else {
                this.RightTree.Insert(newItem);
            }
        }
    }
    public void WalkTree() {
        if (this.LeftTree != null) {
            this.LeftTree.WalkTree();
        }
        Console.WriteLine(this.NodeData.ToString());
        if (this.RightTree != null) {
            this.RightTree.WalkTree();
        }
    }
    public TreeNode NodeData { get; set; }
    public Tree<TreeNode> LeftTree { get; set; }
    public Tree<TreeNode> RightTree { get; set; }

    IEnumerator<TreeNode> IEnumerable<TreeNode>.GetEnumerator() {
        if (this.LeftTree != null) {
            foreach (TreeNode item in this.LeftTree) {
                yield return item;
            }
        }
        yield return this.NodeData;
        if (this.RightTree != null) {
            foreach (TreeNode item in this.RightTree) {
                yield return item;
            }
        }
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
        throw new NotImplementedException();
    }
}
class Employee : IComparable<Employee> {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Department { get; set; }
    public int Id { get; set; }
    public override string ToString() {
        return String.Format("Id: {0}, Name: {1} {2}, Dept: {3}", this.Id, this.FirstName, this.LastName, this.Department);
    }
    int IComparable<Employee>.rupareTo(Employee other) {
        if (other == null)
            return 1;
        if (this.Id > other.Id)
            return 1;
        if (this.Id < other.Id)
            return -1;
        return 0;
    }
}
class Program {
    static void Main() {
        Tree<Employee> empTree = new Tree<Employee>(new Employee { Id = 1, FirstName = "Janet", LastName = "Gates", Department = "IT" });
        empTree.Insert(new Employee { Id = 2, FirstName = "O", LastName = "G", Department = "Marketing" });
        empTree.Insert(new Employee { Id = 4, FirstName = "K", LastName = "H", Department = "IT" });
        empTree.Insert(new Employee { Id = 6, FirstName = "L", LastName = "H", Department = "Sales" });
        empTree.Insert(new Employee { Id = 3, FirstName = "E", LastName = "L", Department = "Sales" });
        empTree.Insert(new Employee { Id = 5, FirstName = "D", LastName = "L", Department = "Marketing" });
        var depts = (from d in empTree select d.Department).Distinct();
        foreach (var dept in depts)
            Console.WriteLine("Department: {0}", dept);
    }
}

Printing the unique Category names

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        List<Product> products = GetProductList(); var categoryNames = (
             from p in products
             select p.Category)
             .Distinct();
        Console.WriteLine("Category names:");
        foreach (var n in categoryNames) {
            Console.WriteLine(n);
        }
    }
    static List<Product> GetProductList() {
        List<Product> empTree = new List<Product>();
        empTree.Add(new Product { ProductName = "A", Category = "O", UnitPrice = 12, UnitsInStock = 5, Total = 36, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "B", Category = "O", UnitPrice = 2, UnitsInStock = 4, Total = 35, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "C", Category = "O", UnitPrice = 112, UnitsInStock = 3, Total = 34, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "D", Category = "O", UnitPrice = 112, UnitsInStock = 0, Total = 33, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "E", Category = "O", UnitPrice = 1112, UnitsInStock = 2, Total = 32, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        empTree.Add(new Product { ProductName = "F", Category = "O", UnitPrice = 11112, UnitsInStock = 0, Total = 31, OrderDate = new DateTime(2005, 1, 1), Id = 1 });
        return empTree;
    }
}
class Product : IComparable<Product> {
    public string ProductName { get; set; }
    public string Category { get; set; }
    public int UnitPrice { get; set; }
    public int UnitsInStock { get; set; }
    public int Total { get; set; }
    public DateTime OrderDate { get; set; }
    public int Id { get; set; }
    public override string ToString() {
        return String.Format("Id: {0}, Name: {1} , Category: {3}", this.Id, this.ProductName, this.Category);
    }
    int IComparable<Product>.rupareTo(Product other) {
        if (other == null)
            return 1;
        if (this.Id > other.Id)
            return 1;
        if (this.Id < other.Id)
            return -1;
        return 0;
    }
}

Set Operators: Distinct

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
    public static void Main() {
        int[] fl = { 2, 2, 3, 5, 5 };
        var uniqueFactors = fl.Distinct();
        Console.WriteLine("Prime factors of 300:");
        foreach (var f in uniqueFactors) {
            Console.WriteLine(f);
        }
    }
}

Use Linq Distinct to get the distinct value in an array

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
   public static void Main(){
            int[] numbers = {1, 1, 2, 3, 3};
            Console.Write(numbers.Distinct());
   }
}