美文网首页
HashSet的使用

HashSet的使用

作者: 价值投机168 | 来源:发表于2020-01-17 11:13 被阅读0次
static void Main(string[] args)
    {
        //1. Defining String Array (Note that the string "mahesh" is repeated) 
        string[] names = new string[] {
            "mahesh",
            "vikram",
            "mahesh",
            "mayur",
            "suprotim",
            "saket",
            "manish"
        };
        //2. Length of Array and Printing array
        Console.WriteLine("Length of Array " + names.Length);
        Console.WriteLine("The Data in Array");
        foreach (var n in names)
        {
            Console.WriteLine(n);
        }
        Console.WriteLine();
        //3. Defining HashSet by passing an Array of string to it
        HashSet<string> hSet = new HashSet<string>(names);
        //4. Count of Elements in HashSet
        Console.WriteLine("Count of Data in HashSet " + hSet.Count);
        //5. Printing Data in HashSet, this will eliminate duplication of "mahesh" 
        Console.WriteLine("Data in HashSet");
        foreach (var n in hSet)
        {
            Console.WriteLine(n);
        }

        Console.WriteLine();
        hSet.Add("test");//add string
        hSet.Add("test");//add string

        HashSet<string> hSet2 = new HashSet<string>(new string[] { "1", "2" });
        hSet.UnionWith(hSet2);//add hSet2

        Console.WriteLine("Data in HashSet");
        foreach (var n in hSet)
        {
            Console.WriteLine(n);
        }

        Console.WriteLine();
        string[] ttt = new string[hSet.Count];
        hSet.CopyTo(ttt);//copy data to array
        Console.WriteLine("ttt.length: " + ttt.Length);
        Console.ReadLine();
    }

相关文章

网友评论

      本文标题:HashSet的使用

      本文链接:https://www.haomeiwen.com/subject/fvjczctx.html