i am having issue grouping object by using linq was wondering if someone can tell me what i am doing wrong here. Also the select function is an extension i grabbed from here (the link) so i can compere the previous and current value, if the value is between a range then i set the value return to the current value.
// Range of values, the first item in the group data, i
var ranges = new List<double> { 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0 };
// Simple class i created
public class CurrencyGroupItemData
{
public string Code { get; set; }
public double TotalStrength { get; set; }
}
var lstCurrencyGroups = new List<CurrencyGroupItemData>();
lstCurrencyGroups.Add(new CurrencyGroupItemData
{ Code = "USD", TotalStrength = 5.0 });
lstCurrencyGroups.Add(new CurrencyGroupItemData
{ Code = "CHF",TotalStrength = 2.14285714285714 });
lstCurrencyGroups.Add(new CurrencyGroupItemData
{ Code = "EUR",TotalStrength = 3.85714285714286 });
lstCurrencyGroups.Add(new CurrencyGroupItemData
{ Code = "GBP",TotalStrength = 3.42857142857143 });
lstCurrencyGroups.Add(new CurrencyGroupItemData
{ Code = "JPY",TotalStrength = 5.71428571428571 });
lstCurrencyGroups.Add(new CurrencyGroupItemData
{ Code = "CAD",TotalStrength = 6.85714285714286 });
lstCurrencyGroups.Add(new CurrencyGroupItemData
{ Code = "AUD",TotalStrength = 4.28571428571429 });
lstCurrencyGroups.Add(new CurrencyGroupItemData
{ Code = "NZD",TotalStrength = 4.71428571428571 });
// compare The total strength of each object, if it's value is between any of ranges above then group item by the range value. for example if the object totalstrength value is 5.7 that value is between 6.0 and 5.0, it's range value would the minimum of the 2 which 5.0, i would group that item by 5.0.
var jjjj01 = lstCurrencyGroups.GroupBy(x => ranges.SelectWithPrev((double r1, double r2, bool isfirst)
=> (isfirst && x.TotalStrength >= r1) ? r1 : (x.TotalStrength <= r1 && x.TotalStrength <= r2) ? r2 : 0.0).ToArray())
.Select(g => new { Rank = g.Key, Count = g.Count() })
.ToList();
// the extension i grabbed from the link above
public static IEnumerable<TResult> SelectWithPrev<TSource, TResult>
(this IEnumerable<TSource> source, Func<TSource, TSource, bool, TResult> projection)
{
using (var iterator = source.GetEnumerator())
{
var isfirst = true;
var previous = default(TSource);
while (iterator.MoveNext())
{
yield return projection(iterator.Current, previous, isfirst);
isfirst = false;
previous = iterator.Current;
}
}
}