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

回答編集履歴

2

IComparable実装パターンを追記

2018/07/23 09:21

投稿

YamakawaJunichi
YamakawaJunichi

スコア632

answer CHANGED
@@ -5,4 +5,38 @@
5
5
 
6
6
  filelist.Aggregate((result, next) => result.Length > next.Length ? result : next);
7
7
 
8
+ ```
9
+
10
+ 追記
11
+ 無理矢理FileInfoにIComparableを実装するならこんな感じでしょうか。
12
+ 自作クラスなら自然な形で実装できるのですが・・・
13
+
14
+ 余談ですが、FileInfoに拡張メソッドでCompareToを定義してみましたがやはりダメでした。
15
+
16
+ ```C#
17
+
18
+ filelist.Select(p => new FileInfoWrapper(p)).Max().FileInfo;
19
+
20
+ class FileInfoWrapper : IComparable<FileInfoWrapper>
21
+ {
22
+ public FileInfo FileInfo { get; }
23
+ public FileInfoWrapper(FileInfo fileInfo) => FileInfo = fileInfo;
24
+
25
+ public int CompareTo(FileInfoWrapper other)
26
+ {
27
+ if (FileInfo.Length == other.FileInfo.Length)
28
+ {
29
+ return 0;
30
+ }
31
+ else if (FileInfo.Length > other.FileInfo.Length)
32
+ {
33
+ return 1;
34
+ }
35
+ else
36
+ {
37
+ return -1;
38
+ }
39
+ }
40
+ }
41
+
8
42
  ```

1

変数の誤りを修正

2018/07/23 09:21

投稿

YamakawaJunichi
YamakawaJunichi

スコア632

answer CHANGED
@@ -3,6 +3,6 @@
3
3
 
4
4
  ```C#
5
5
 
6
- filelist.Aggregate((result, next) => result.ID > next.ID ? result : next);
6
+ filelist.Aggregate((result, next) => result.Length > next.Length ? result : next);
7
7
 
8
8
  ```