Ok, what can I suggest so far.
Firstly: you've got a lot of Add
's.
In general default List<T>
is not the best datastructure for lot of Add
's, because internally it's implemented as array which is destroyed and copied to larger one when it's full.
Two options are possible:
- create list with predefined capacity: List<string> allApps = new List<string>(countOfApps);
. This one is good if you can roughly calculate count of items that are to be added to list in advance.
- use LinkedList<string> allApps = new LinkedList<string>()
. LinkedList does adding new items pretty fast.
Same stuff is true for List<string> Appname = new List<string>();
list.
Secondly: at the beginning you've got list which is distinct
-ed and then converted to list on each iteration of foreach
-loop, while the newly constructed list is not used in that loop. So here you can move that distinct->tolist
code out of the loop, the code logic won't change, but performance will increase.
So far I can suggest the following code:
LinkedList<string> allApps2 = new LinkedList<string>();// linkedlist here
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;
foreach(var userapp in usersapps)// add _all the apps_ to list. Will be distinct-ed later
{
allApps2.AddLast(userapp);// don't worry, it works for O(1)
}
}
var allApps = allApps2.Distinct().ToList();
int countapps = 0;
LinkedList<string> Appname2 = new LinkedList<string>();// linkedlist here
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)
{
Appname2.AddLast(appList.ElementAt(y).AppName);// and here
}
}
}
var AppName = Appname2.ToList();// and you've got you List<string> as the result
Please, try this code and let me know how it works(though I think it should work considerably faster).
Hope this helps.
UPDATE
Finally I'm home, sorry for delay. I played with code a bit and made it faster by rewriting last for
into this:
foreach (var app in appList)
{
foreach (string li in allApps)
{
bool istrueapp = app.AppName.Equals(li);
if (istrueapp)
{
Appname2.AddLast(app.AppName);
}
}
}
That gave great speed-up, at least on my machine(r).
Please check whether it's faster on your environment.
Hope that helps.