This repository has been archived by the owner on Jul 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 196
/
Copy pathLINQ.cs
102 lines (81 loc) · 2.48 KB
/
LINQ.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Linq
{
public static class LINQ
{
public static int Count<TSource>(this IEnumerable<TSource> source, Predicate<TSource> predicate)
{
int count = 0;
foreach (var item in source)
{
if (predicate(item))
count++;
}
return count;
}
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource target)
{
foreach (var item in source)
{
if (item.Equals(target))
return true;
}
return false;
}
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Predicate<TSource> predicate)
{
foreach (var item in source)
{
if (predicate(item))
return item;
}
return default(TSource);
}
public static int Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int> getter)
{
int sum = 0;
foreach (var item in source)
{
sum += getter(item);
}
return sum;
}
public static IEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> getter)
where TKey : IComparable<TKey>
{
var items = new List<TSource>();
foreach (var i in source)
{
items.Add(i);
}
items.Sort(new DelegateComparer<TSource, TKey>(getter));
return items;
}
public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source)
{
if (source is TSource[])
return source as TSource[];
var items = new List<TSource>();
foreach (var i in source)
{
items.Add(i);
}
return items.ToArray();
}
}
class DelegateComparer<TSource, TKey> : IComparer<TSource>
where TKey : IComparable<TKey>
{
private Func<TSource, TKey> m_Getter;
public DelegateComparer(Func<TSource, TKey> getter)
{
m_Getter = getter;
}
public int Compare(TSource x, TSource y)
{
return m_Getter(x).CompareTo(m_Getter(y));
}
}
}