teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

4

ListExtensionに名前を変更

2016/12/16 07:26

投稿

haru666
haru666

スコア1593

answer CHANGED
@@ -52,9 +52,9 @@
52
52
  もう一つ。1から10000まで隙間なくデータが埋まっているならWhere句よりGetRangeを使うこともできます。
53
53
  リストはコピーされるものの、こちらはリスト全体を舐めないですむので場合によっては高速になります。
54
54
  ```
55
- public static class MyItemExtension
55
+ public static class ListExtension
56
56
  {
57
- public static IList<MyItem> Sampling(this IEnumerable<MyItem> items, int threshold)
57
+ public static List<T> Sampling(this List<T> items, int threshold)
58
58
  {
59
59
  // startIndexを計算で求められる場合にはそうする。
60
60
  // 1から10000のリストなので追加で1引いた数にすれば良い。

3

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

2016/12/16 07:26

投稿

haru666
haru666

スコア1593

answer CHANGED
@@ -46,4 +46,21 @@
46
46
  SomeFunction(MyCollection.Sampling(100));
47
47
  // 250~350受け取りたい処理にパス
48
48
  SomeFunction(MyCollection.Sampling(300));
49
- ```
49
+ ```
50
+
51
+ #パフォーマンス上のことで更に追記
52
+ もう一つ。1から10000まで隙間なくデータが埋まっているならWhere句よりGetRangeを使うこともできます。
53
+ リストはコピーされるものの、こちらはリスト全体を舐めないですむので場合によっては高速になります。
54
+ ```
55
+ public static class MyItemExtension
56
+ {
57
+ public static IList<MyItem> Sampling(this IEnumerable<MyItem> items, int threshold)
58
+ {
59
+ // startIndexを計算で求められる場合にはそうする。
60
+ // 1から10000のリストなので追加で1引いた数にすれば良い。
61
+ int begin = threshold - 51;
62
+ return items.GetRange(begin, 101); // 50 ~ 150は101要素だから。
63
+ }
64
+ }
65
+ ```
66
+ ※コレクションによっては最善の方法でキー探索とかしてくれるかもしれませんが、わかりませんしね。。

2

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

2016/12/16 07:25

投稿

haru666
haru666

スコア1593

answer CHANGED
@@ -31,7 +31,7 @@
31
31
 
32
32
  ```C#
33
33
  // コレクションを最初に作る時にソートしておく
34
- MyCollection = new Collection<MyItem>(DataSource.OrderBy(item => item.id));
34
+ MyCollection = new Collection<MyItem>(DataSource.OrderBy(item => item.Id));
35
35
 
36
36
  // 入力されたら前後50の範囲を返す関数を作っとく。
37
37
  public static class MyItemExtension

1

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

2016/12/16 07:14

投稿

haru666
haru666

スコア1593

answer CHANGED
@@ -20,4 +20,30 @@
20
20
  {
21
21
  Console.WriteLine($"{number}");
22
22
  }
23
+ ```
24
+
25
+ #補足への回答
26
+ 先にコレクションをソートしておけば大丈夫ですよ。
27
+ 最初に言った通りWhere句で並び順が崩れるなんていうことは**普通ありません**。
28
+
29
+ 必要に応じてWhereメソッドを呼び出すというのを何度もやったらいいです。
30
+ もしも現在の実装で並び順が崩れるため、パフォーマンスを考えてWhere句の後にOrderByしない解決方法を必要としている場合はコードを添付してください。
31
+
32
+ ```C#
33
+ // コレクションを最初に作る時にソートしておく
34
+ MyCollection = new Collection<MyItem>(DataSource.OrderBy(item => item.id));
35
+
36
+ // 入力されたら前後50の範囲を返す関数を作っとく。
37
+ public static class MyItemExtension
38
+ {
39
+ public static IEnumerable<MyItem> Sampling(this IEnumerable<MyItem> items, int threshold)
40
+ {
41
+ return items.Where(item => (threshold - 50) <= item.Id && item.Id <= (threshold + 50));
42
+ }
43
+ }
44
+
45
+ // 50~150受け取りたい処理にパス
46
+ SomeFunction(MyCollection.Sampling(100));
47
+ // 250~350受け取りたい処理にパス
48
+ SomeFunction(MyCollection.Sampling(300));
23
49
  ```