C#如何为泛型添加不重复项

C#如何为泛型添加不重复项,第1张

您已经实现了Equals方法了,那么在添加到范型集合的时候调用该方法检查。List<Class1>list = new List<Class1>()

list.Add(c1)

list.Add(c2)

list.Add(c3)

.

.

.

list.Add(cn)

Class1 c = new Class1()

bool isDuplicate = false

foreach(Class1 item in list)

{

if(c.Euqals(item))

{

isDuplicate = true

break

}

}

if(! isDuplicate)

{

list.Add(c)

}

见以下代码和注释

using System

using System.Collections.Generic

using System.Linq

namespace ConsoleApplication11

{

    class Word

    {

        // 字

        public char C { get set }

        // 出现的次数

        public int Count { get set }

    }

    class Program

    {

        static void Main(string[] args)

        {

            //输入一句话

            string s = Console.ReadLine()

            // 集合

            Dictionary<char, Word> words = new Dictionary<char, Word>()

            // 添加到集合words

            foreach (char c in s)

            {

                if(words.ContainsKey(c))

                {

                    words[c].Count++

                }

                else

                {

                    Word word = new Word { C = c, Count = 1 }

                    words.Add(c, word)

                }

            }

            // 使用Linq,查找出现次数最大值

            int max = words.Values.Max(x => x.Count)

            // 使用Linq,查找最大值对应的元素。注意:最大值也许有多个

            var qry = words.Values.Where(x => x.Count == max)

            // 输出

            Console.WriteLine("频率最高的字")

            foreach(var q in qry )

            {

                Console.WriteLine("{0}:{1}", q.C, q.Count)

            }

        }

    }

}

运行

(1)输入:我我我我你你你你

(2)输入:我的你的他的我们的他们的

我不知道你为什么要这样使用,不过你可以改成这样

Cells c=new Cells()

List<Cells>r=new List<Cells>()

r.add(c)

List<List<Cells>>list = new List<List<Cells>>()

list.add(r)

如果我说的符合你的要求,就给我分吧。- -


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/bake/11751332.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-18
下一篇2023-05-18

发表评论

登录后才能评论

评论列表(0条)

    保存