My intent is to find the minimum value and associated ID of either a custom class or KeyValue pair. Below is the small console app. I can locate the values I need using the sort function as shown ( delegate ). But I think there may be a cleaner way using lamda expressions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FindClosestPart2
{
class Program
{
class IdDelta
{
public int ID {get;set;}
public float Delta { get; set; }
}
static void Main(string[] args)
{
doMe();
}
private static void doMe()
{ // create the list
// then sort to find least value of all... or find the ID once the minValue located.
var listKeyDeltas = new List<KeyValuePair<int,float>>();;
Random xrandom = new Random();
IdDelta[] ideltas = new IdDelta[50] ;
for (int i = 0; i < 50; i++)
{
double trouble =xrandom.NextDouble();
float calcAbs = Convert.ToSingle(trouble);
var keyDelta = new KeyValuePair<int, float>(i, calcAbs);
listKeyDeltas.Add(keyDelta);
ideltas[i] = new IdDelta();
ideltas[i].Delta = calcAbs;
ideltas[i].ID = i;
}
float minDelta = ideltas.Min(IdDelta => IdDelta.Delta); // works... ( but now need ID... )
IdDelta foome = new IdDelta();
// var fooX = new System.Collections.Generic.IEnumerable<FindClosestPart2.Program.IdDelta>();
// foome = ideltas.Where(IdDelta => IdDelta.Delta == minDelta);
// listKeyDeltas.Min< ?? // is it possible to write either as lamda expression ??
listKeyDeltas.Sort(Compare2); // this works and gets everything I wanted
Console.WriteLine("keyId : " + listKeyDeltas[0].Key +" with Min value of " + listKeyDeltas[0].Value);
foreach (var pair in listKeyDeltas)
{
Console.WriteLine(pair);
}
Console.ReadKey();
}
static int Compare2(KeyValuePair<int, float> a, KeyValuePair<int, float> b)
{
return a.Value.CompareTo(b.Value);
}
}
}
Thanks !
andrew