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

来源:互联网 发布:java调用sql存储过程 编辑:程序博客网 时间:2024/05/22 06:39

我想便利一个数组中如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);
                            }
                        }
                    }
                }
            }