Wednesday, 1 October 2014

How to find dictionary duplicate values in C#

For Reference:

//initialize a dictionary with keys and values.    
Dictionary<int, string> plants = new Dictionary<int, string>() {    
    {1,"Speckled Alder"},    
    {2,"Apple of Sodom"},    
    {3,"Hairy Bittercress"},    
    {4,"Pennsylvania Blackberry"},    
    {5,"Apple of Sodom"},    
    {6,"Water Birch"},    
    {7,"Meadow Cabbage"},    
    {8,"Water Birch"}    
};  
  
Response.Write("<b>dictionary elements........</b><br />");
        
//loop dictionary all elements   
foreach (KeyValuePair<int, string> pair in plants)  
{
    Response.Write(pair.Key + "....."+ pair.Value+"<br />");
}  
  
//find dictionary duplicate values.  
var duplicateValues = plants.GroupBy(x => x.Value).Where(x => x.Count() > 1);

Response.Write("<br /><b>dictionary duplicate values..........</b><br />");

//loop dictionary duplicate values only            
foreach(var item in duplicateValues)  
{
    Response.Write(item.Key+"<br />");
}   


1.
counties = XDocument.Load(HttpContext.Current.Server.MapPath("/data/counties.xml"))
.Descendants("Row")
.GroupBy(i => i.Attribute("Code").Value)
.Where(g => g.Count() == 1)
.Select(g => new { Code = g.Key, Desc = g.First().Attribute("Descrip").Value })
.ToDictionary(x => x.Code, x => x.Desc);
2. 

How to Remove Duplicates and Get Distinct records from List using LINQ?

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace AbundantCode
{
internal class Program
{
//How to Remove Duplicates and Get Distinct records from List using LINQ ?
private static void Main(string[] args)
{
List<Employee> employees = new List<Employee>()
{
new Employee { EmpID = 1 , Name ="AC"},
new Employee { EmpID = 2 , Name ="Peter"},
new Employee { EmpID = 3 , Name ="Michael"},
new Employee { EmpID = 3 , Name ="Michael"}
};
//Gets the Distinct List
var DistinctItems = employees.GroupBy(x => x.EmpID).Select(y => y.First());
foreach(var item in DistinctItems)
Console.WriteLine(item.Name);
Console.ReadLine();
}
}
public class Employee
{
public string Name { get; set; }
public int EmpID { get; set; }
}
}
3. 

How to find the duplicate items in a list?

string[] ss ={ "1","1","1"};
            List<string> myList = new List<string>();
 
 
            foreach (String s in&nbsp;ss)
            {
                if (!myList.Contains(s))
                {
                 myList.Add(s);
                }
            }
 
            foreach (String s in&nbsp;myList)
            {
                Console.WriteLine(s);
            }

No comments:

Post a Comment