回答編集履歴

4

ListExtensionに名前を変更

2016/12/16 07:26

投稿

haru666
haru666

スコア1591

test CHANGED
@@ -106,11 +106,11 @@
106
106
 
107
107
  ```
108
108
 
109
- public static class MyItemExtension
109
+ public static class ListExtension
110
110
 
111
111
  {
112
112
 
113
- public static IList<MyItem> Sampling(this IEnumerable<MyItem> items, int threshold)
113
+ public static List<T> Sampling(this List<T> items, int threshold)
114
114
 
115
115
  {
116
116
 

3

パフォーマンス上の追記を追加

2016/12/16 07:26

投稿

haru666
haru666

スコア1591

test CHANGED
@@ -95,3 +95,37 @@
95
95
  SomeFunction(MyCollection.Sampling(300));
96
96
 
97
97
  ```
98
+
99
+
100
+
101
+ #パフォーマンス上のことで更に追記
102
+
103
+ もう一つ。1から10000まで隙間なくデータが埋まっているならWhere句よりGetRangeを使うこともできます。
104
+
105
+ リストはコピーされるものの、こちらはリスト全体を舐めないですむので場合によっては高速になります。
106
+
107
+ ```
108
+
109
+ public static class MyItemExtension
110
+
111
+ {
112
+
113
+ public static IList<MyItem> Sampling(this IEnumerable<MyItem> items, int threshold)
114
+
115
+ {
116
+
117
+ // startIndexを計算で求められる場合にはそうする。
118
+
119
+ // 1から10000のリストなので追加で1引いた数にすれば良い。
120
+
121
+ int begin = threshold - 51;
122
+
123
+ return items.GetRange(begin, 101); // 50 ~ 150は101要素だから。
124
+
125
+ }
126
+
127
+ }
128
+
129
+ ```
130
+
131
+ ※コレクションによっては最善の方法でキー探索とかしてくれるかもしれませんが、わかりませんしね。。

2

idをIdに変更(C#的な意味で)

2016/12/16 07:25

投稿

haru666
haru666

スコア1591

test CHANGED
@@ -64,7 +64,7 @@
64
64
 
65
65
  // コレクションを最初に作る時にソートしておく
66
66
 
67
- MyCollection = new Collection<MyItem>(DataSource.OrderBy(item => item.id));
67
+ MyCollection = new Collection<MyItem>(DataSource.OrderBy(item => item.Id));
68
68
 
69
69
 
70
70
 

1

追記された補足質問への回答を追加

2016/12/16 07:14

投稿

haru666
haru666

スコア1591

test CHANGED
@@ -43,3 +43,55 @@
43
43
  }
44
44
 
45
45
  ```
46
+
47
+
48
+
49
+ #補足への回答
50
+
51
+ 先にコレクションをソートしておけば大丈夫ですよ。
52
+
53
+ 最初に言った通りWhere句で並び順が崩れるなんていうことは**普通ありません**。
54
+
55
+
56
+
57
+ 必要に応じてWhereメソッドを呼び出すというのを何度もやったらいいです。
58
+
59
+ もしも現在の実装で並び順が崩れるため、パフォーマンスを考えてWhere句の後にOrderByしない解決方法を必要としている場合はコードを添付してください。
60
+
61
+
62
+
63
+ ```C#
64
+
65
+ // コレクションを最初に作る時にソートしておく
66
+
67
+ MyCollection = new Collection<MyItem>(DataSource.OrderBy(item => item.id));
68
+
69
+
70
+
71
+ // 入力されたら前後50の範囲を返す関数を作っとく。
72
+
73
+ public static class MyItemExtension
74
+
75
+ {
76
+
77
+ public static IEnumerable<MyItem> Sampling(this IEnumerable<MyItem> items, int threshold)
78
+
79
+ {
80
+
81
+ return items.Where(item => (threshold - 50) <= item.Id && item.Id <= (threshold + 50));
82
+
83
+ }
84
+
85
+ }
86
+
87
+
88
+
89
+ // 50~150受け取りたい処理にパス
90
+
91
+ SomeFunction(MyCollection.Sampling(100));
92
+
93
+ // 250~350受け取りたい処理にパス
94
+
95
+ SomeFunction(MyCollection.Sampling(300));
96
+
97
+ ```