用Dictionary 挺好还支持泛型
解决方案 »
- 怎样识别,甲图是不是乙图的一部分?
- C#请教,如何在同一个pixturebox中添加多个mouseclick事件
- DataGridViewTextBoxColumn 没绑定进行统计问题
- SilverLight页面怎么使用水晶报表
- 错误:并非所有的代码路径都返回值,这是怎么回事呢?
- 请教高手 ~!!
- 能获得exe的返回值吗
- 如何始终监视数据库中某一个字段的变化?
- 急!急!急!请问如何在Oracle通过C#创建新的存储过程(不是调用)
- 3des 加密算法的key,iv有什么要求呀,随便写一个总是不行
- 开发的windows服务,导致登录操作系统后,只显示蓝色背景,无法显示桌面,请大家帮助
- winfrom中上传文件问题
List<string> a;替换为Dictionary<int, string> a;
添加的地方替换为
a.Add(a.GetHashCode(), a);
搜索的地方替换为
if(a.ContainsKey(a.GetHashCode())
{
...
}
这样可以缓存hashcode避免List的Contains方法要调用每个元素的GetHashCode方法。没实际测试,理论上可行。楼主你试试。
分多个多线程查询
Dictionary<int, string> b = new Dictionary<int, string>();
Dictionary<int, string> c = new Dictionary<int, string>();foreach (int acode in a.Keys)
{
if (b.ContainsKey(acode))
{
}
else
{
c.Add(acode, a[acode]);
}
}
if(a.ContainsKey(a.GetHashCode())
{
...
}
应该改为
if(b.ContainsKey(a.GetHashCode())
{
...
}
吧?
string newstring = "aaa";
a.Add(newstring.GetHashCode(),newstring);
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); List<string> list1 = Enumerable.Range(0, 10000).Select(s => s.ToString()).ToList();
List<string> list2 = Enumerable.Range(0, 10000).Select(s => s.ToString()).ToList();
watch.Start();
Dictionary<int, string> dic1 = list1.ToDictionary(c => c.GetHashCode());
Dictionary<int, string> dic2 = list2.ToDictionary(c => c.GetHashCode());
List<string> resut = new List<string>();
foreach (System.Collections.Generic.KeyValuePair<int, string> item in dic1)
{
if (dic2.ContainsKey(item.Key))
{
resut.Add(item.Value);
}
}
watch.Stop();
System.Console.WriteLine(watch.ElapsedMilliseconds.ToString());
//结果7
resut .Clear ();
watch.Start();
foreach (string str in list1)
{
if (list2 .Contains (str))
resut .Add (str);
}
watch.Stop();
System.Console.WriteLine(watch.ElapsedMilliseconds.ToString());
//结果 948
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> a = new List<string> { "Edwin","edwin","wed","red","Haha"};
for (int i = 0; i < 100000; i++)
{
a.Add(System.Guid.NewGuid().ToString().Substring(0,6));
}
System.Console.WriteLine(a.Count);
List<string> b = new List<string> { "Edwin", "edwin", "wed", "red", "Haha" ,"54544","9494","I CALL"};
for (int i = 0; i < 10000; i++)
{
b.Add(System.Guid.NewGuid().ToString().Substring(0, 6));
}
System.Console.WriteLine(b.Count);
List<string> temp = null;
Stopwatch sw = new Stopwatch();
sw.Start();
if (a.Count > b.Count)
{
var v = from p in a where b.Contains(p) select p;
temp = v.ToList();
}
else
{
var v = from p in b where a.Contains(p) select p;
temp = v.ToList();
}
sw.Stop();
System.Console.WriteLine("----------------------------------------------");
System.Console.WriteLine(temp.Count);
System.Console.WriteLine(sw.Elapsed.Milliseconds / 1000d);
System.Console.ReadLine();
}
}
}100005
10000
68
0.261