您的位置:首页 > 其它

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

2011-11-30 00:42 295 查看
我想便利一个数组中如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);

}

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐