开发者

Most efficient way to see if a string exists in a collection stored in ASP.Net Session State

I have an ASP.Net app that retrieves a collection of roles for a given user. Each role is a string.开发者_如何学运维 There's rarely more than 2-3 roles for any one person.

I wanted to store the colelction of roles in Session state to save the time accessing the DB on each request.

I basically want to write code that checks if a given string exists in the collection to test if the user has that role or not.

My question is...what's the best way to do this? Is an array the best collection to store the role strings in Session with? Or is a dictionary better? I figure an array will take less memory (I don't really need a key + value) although a dictionary might lookup faster.

What would you suggest?


Don't worry about optimization until its time to optimize. An array is fine. As far as determining if the string exists, I'd compare each element in the array using Equals using StringComparison.OrdinalIgnoreCase, as your roles probably will be culturally neutral.


"foo" == "bar" is an Ordinal comparison. Case matters. For roles, you usually don't care about case (is an 'administrator' the same thing as an 'Administrator'? In any rational world the answer is yes), so you want to compare using an Ordinal comparison that ignores case, or OrdinalIgnoreCase.


A HashSet<string> technically has faster lookups than a List<string>. It's basically a Dictionary without any values. However, when we're talking about only 2-3 items, I don't think it matters much whether you use a List or a HashSet.


A List<string> would probably be best. If you know for a fact that there will never be more than (say) 3, then a string array might be slightly better - probably not enough to make a difference. The hashing required for a dictionary is probably overkill for such a small list.


Something like this?

//string as a generic list
List<string> roles;

//check if list contains a certain role
roles.Contains(TheRoleToCheck);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜