List<string> allApps = new List<string>();
roster = MURLEngine.GetUserFriendDetails(token, userId);
var usersfriends = from elements in roster.RosterEntries
where elements[0] == 'm' && elements[1] >= '0' && elements[1] <= '9'
select elements;
foreach (string userid in usersfriends)
{
roster = MURLEngine.GetUserFriendDetails(token, userid);
var usersapps = from elements in roster.RosterEntries
where elements[0] != 'm'
select elements;
allApps.AddRange(usersapps);
allApps = allApps.Distinct().ToList();
}
int countapps = 0;
List<string> Appname = new List<string>();
countapps = appList.Count();
for (int y = 0; y < countapps; y++)
{
foreach (string li in allApps) //
{
bool istrueapp = appList.ElementAt(y).AppName.Equals(li);
if (istrueapp == true)
{
Appname.Add(appList.ElementAt(y).AppName);
}
}
}
在上面的代码中,我首先得到一个字符串列表,即 usersfriends,然后根据这些 ID 得到用户的应用程序列表,然后将所有用户的所有应用程序添加到另一个列表,即 allApps,因此整个过程很慢,使用列表执行此操作大约需要 20 秒。也尝试使用 HashSet 和 SortedSet,但速度更慢。
我的问题是在这种情况下我应该使用什么数据结构??
真的对我有帮助
最佳答案
关于 LINQ,我最喜欢的一点是它可以让你描述你想做什么,而不是让你写一堆模糊你目标的循环。这是您的代码的重构版本,我认为它非常清晰,并且在我的测试平台中运行速度更快(0.5 秒对 ~15 秒)。
// create a hashset for fast confirmation of app names
var realAppNames = new HashSet<string>(appList.Select(a => a.AppName));
var roster = MURLEngine.GetUserFriendDetails(token, userId);
// get the ids of all friends
var friendIds = roster.RosterEntries
.Where (e => e[0] == 'm' && e[1] >= '0' && e[1] <= '9');
var apps =
friendIds
// get the rosters for all friends
.SelectMany (friendId => MURLEngine.GetUserFriendDetails(token, friendId)).RosterEntries)
// include the original user's roster so we get their apps too
.Concat(roster.RosterEntries)
// filter down to apps only
.Where (name => name[0] != 'm' && realAppNames.Contains(name))
// remove duplicates
.Distinct()
// we're done!
.ToList();
关于c# - 基于比较 c# 将元素添加到列表时使用的最佳数据结构是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18857573/