c# - 基于比较 c# 将元素添加到列表时使用的最佳数据结构是什么

标签 c# list data-structures hashset sortedset

  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/

相关文章:

json - 在 Flutter 中从 JSON 创建列表

java - 什么是表示比枚举更复杂但又不完全是类的字段的良好数据结构?

c# - 如何使用 signalr 将 json 对象发送到 .net 服务器

c# - jQuery 自动完成、MVC4 和 WebAPI

java - 在 Java 类中创建对象列表 - 更好的方法

java - 在双链表中插入节点

data-structures - Redis中的最优存储结构

c# - 获取Unity中多个GameObject之间的中心点

c# - 如何序列化模型,在 ajax 请求中将其传递给 MVC Controller

java - 如何将第一个列表中未包含在具有重复值的第二个列表中的元素保存在列表中?