Trouver la valeur minimale et maximale à partir d'une liste clef/valeur en C# et VB.Net
J'ai un tableau multidimensionnel avec essentiellement une paire clé / valeur. Je voudrais additionner toutes les valeurs en fonction de la clé, puis choisir les valeurs min et max à partir de cela.
VB.Net
01.
Protected
Sub
Page_Load(
ByVal
sender
As
Object
,
ByVal
e
As
EventArgs)
Handles
Me
.Load
02.
Dim
totals =
New
List(Of KeyValuePair(Of
String
,
Double
))()
03.
totals.Add(
New
KeyValuePair(Of
String
,
Double
)(
"Floppy"
, 12.5))
04.
totals.Add(
New
KeyValuePair(Of
String
,
Double
)(
"Layn"
, 8.3))
05.
totals.Add(
New
KeyValuePair(Of
String
,
Double
)(
"Syntetik"
, 51.32))
06.
totals.Add(
New
KeyValuePair(Of
String
,
Double
)(
"Blyat"
, 3.0))
07.
Dim
minValue
As
Double
= 0, maxValue
As
Double
= 0
08.
Dim
maxKey
As
String
=
""
, minKey
As
String
=
""
09.
10.
For
Each
item1
As
KeyValuePair(Of
String
,
Double
)
In
totals
11.
If
maxValue < item1.Value
Then
12.
maxKey = item1.Key
13.
maxValue = item1.Value
14.
End
If
15.
Next
16.
17.
minValue = maxValue
18.
19.
For
Each
item
As
KeyValuePair(Of
String
,
Double
)
In
totals
20.
If
item.Value <> 0
Then
21.
If
minValue > item.Value
Then
22.
minKey = item.Key
23.
minValue = item.Value
24.
End
If
25.
End
If
26.
Next
27.
Response.Write(minKey &
" Minimum value is : "
& minValue &
" <br />"
& maxKey &
" Maximum Value is : "
& maxValue)
28.
End
Sub
C#
01.
protected
void
Page_Load(
object
sender, EventArgs e)
02.
{
03.
var totals =
new
List<KeyValuePair<
string
,
double
>>();
04.
totals.Add(
new
KeyValuePair<
string
,
double
>(
"Pazer"
, 4.21));
05.
totals.Add(
new
KeyValuePair<
string
,
double
>(
"DubZ"
, 3.14));
06.
totals.Add(
new
KeyValuePair<
string
,
double
>(
"DocBoom"
, 12.72));
07.
totals.Add(
new
KeyValuePair<
string
,
double
>(
"RetardZ"
, 0.1));
08.
double
minValue = 0;
09.
double
maxValue = 0;
10.
string
maxKey =
""
;
11.
string
minKey =
""
;
12.
foreach
(KeyValuePair<
string
,
double
> item1
in
totals)
13.
{
14.
if
(maxValue < item1.Value)
15.
{
16.
maxKey = item1.Key;
17.
maxValue = item1.Value;
18.
}
19.
}
20.
21.
minValue = maxValue;
22.
foreach
(KeyValuePair<
string
,
double
> item
in
totals)
23.
{
24.
if
(item.Value != 0)
25.
{
26.
if
(minValue > item.Value)
27.
{
28.
29.
minKey = item.Key;
30.
minValue = item.Value;
31.
}
32.
}
33.
}
34.
Response.Write(minKey +
" Minimum value is : "
+ minValue +
" <br />"
+ maxKey +
" Maximum Value is : "
+ maxValue);
35.
}