1 private void simpleButton1_Click(object sender, EventArgs e)
2 {
3 List<TESTCLASS> list = new List<TESTCLASS>();
4 int[] ary = new int[] { 1,1,1,1,2,2,2,3,3,3,4,4,4};
5
6 for (int i = 0; i < 100; i++)
7 {
8 list.Add(new TESTCLASS(i, i));
9 }
10
11 var list2 = from t in list
12 select new TESTCLASS(t.X, t.Y);
13
14 foreach (var t in list2)
15 {
16 while (true)
17 {
18 MessageBox.Show(t.GetHashCode().ToString() + ":" + list2.ToList()[0].GetHashCode().ToString());
19 MessageBox.Show(list2.ToList().IndexOf(t).ToString());
20 return; ;
21 }
22 }
23
24 }
25
26 public class TESTCLASS
27 {
28 public TESTCLASS(int x, int y)
29 {
30 this.x = x;
31 this.y = y;
32 }
33
34 int x;
35 public int X
36 {
37 get
38 {
39 return x;
40 }
41 set
42 {
43 x = value;
44 }
45 }
46
47 int y;
48 public int Y
49 {
50 get
51 {
52 return y;
53 }
54 set
55 {
56 y = value;
57 }
58 }
59 }
60
GetHashCode的值都不一样,检索结果为-1,按理说不应该呀,我是从list2集合中判读list2中的对象呀 。2 {
3 List<TESTCLASS> list = new List<TESTCLASS>();
4 int[] ary = new int[] { 1,1,1,1,2,2,2,3,3,3,4,4,4};
5
6 for (int i = 0; i < 100; i++)
7 {
8 list.Add(new TESTCLASS(i, i));
9 }
10
11 var list2 = from t in list
12 select new TESTCLASS(t.X, t.Y);
13
14 foreach (var t in list2)
15 {
16 while (true)
17 {
18 MessageBox.Show(t.GetHashCode().ToString() + ":" + list2.ToList()[0].GetHashCode().ToString());
19 MessageBox.Show(list2.ToList().IndexOf(t).ToString());
20 return; ;
21 }
22 }
23
24 }
25
26 public class TESTCLASS
27 {
28 public TESTCLASS(int x, int y)
29 {
30 this.x = x;
31 this.y = y;
32 }
33
34 int x;
35 public int X
36 {
37 get
38 {
39 return x;
40 }
41 set
42 {
43 x = value;
44 }
45 }
46
47 int y;
48 public int Y
49 {
50 get
51 {
52 return y;
53 }
54 set
55 {
56 y = value;
57 }
58 }
59 }
60
关键代码如果改成如下方式就可以了,先将将结果保存到一个集合中就可以了
1 var list2 = from t in list
2 select new TESTCLASS(t.X, t.Y);
3 var list3 = list2.ToList();
4 foreach (var t in list3)
5 {
6 while (true)
7 {
8 MessageBox.Show(t.GetHashCode().ToString() + ":" + list3.ToList()[0].GetHashCode().ToString());
9 MessageBox.Show(list3.ToList().IndexOf(t).ToString());
10 return; ;
11 }
12 }
13
原因不知道,只是发现了这个问题,如果那位大侠知道,就跟个贴,谢谢2 select new TESTCLASS(t.X, t.Y);
3 var list3 = list2.ToList();
4 foreach (var t in list3)
5 {
6 while (true)
7 {
8 MessageBox.Show(t.GetHashCode().ToString() + ":" + list3.ToList()[0].GetHashCode().ToString());
9 MessageBox.Show(list3.ToList().IndexOf(t).ToString());
10 return; ;
11 }
12 }
13