便利一个集合或数组中重复出现的数据的名字和个数

我想便利一个数组中如1,2,3,2,4,5,6,4,2,1,5中的元素的相同的元素的个数,然后把它们的还一一对应的保存起来

形如:1 有2个,2有3个,3有1个,4有2个,5有2个,6有一个

想了一节课终于解决了……

我先定义了一个类,想要便利用户的文章的个数:

 public class UserContent
    {
        public string Username { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }

然后我又定义了一个记录用户文章数目的信息类:

 public class ContentAccount
    {
        public string UserName { get; set; }
        public int ContentCount { get; set; }

    }

这时我需要使用泛型来解决这个问题:

 ObservableCollection<UserContent> UserInfo = new ObservableCollection<UserContent>();

ObservableCollection<ContentAccount> temp = new ObservableCollection<ContentAccount>();
            foreach (UserContent usercontent in UserInfo)
            {
                ContentAccount contentaccount = new ContentAccount();
                int tempcount = temp.Count;
                if (tempcount == 0)
                {
                    contentaccount.UserName = usercontent.Username;
                    contentaccount.ContentCount = 1;
                    temp.Add(contentaccount);
                }
                else
                {
                    for (int i = 0; i < tempcount; i++)
                    {
                        if (usercontent.Username == temp[i].UserName)
                        {
                            temp[i].ContentCount += 1;
                            break;
                        }
                        else
                        {
                            if (i == tempcount - 1)
                            {
                                contentaccount.UserName = usercontent.Username;
                                contentaccount.ContentCount = 1;
                                temp.Add(contentaccount);
                            }
                        }
                    }
                }
            }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值