I need the best way to do prefix based operations in c#.
I have the following data.
prefix price parent_id
1 0.0031 6
1201 0.0021 29
1201555 0.0061 6
1204 0.0014 29
12045 0.0020 6
1205 0.0021 6
Resultant should look like
prefix price parent_id
1 0.0031 6
1201 0.0021 29
1204 0.0014 29
1205 0.0021 6
So result should avoid a prefix with more cost than its sub-prefix, but if bigger prefix belongs to same parent of sub prefix that has lowest cost then it should consider it as well.
I have made it work using following code, but it is taking too much time. It takes around 1 minute to process 5000 prefixes but I have around 150000.
public class Prefixes
{
public string prefix { get; set; }
public decimal price { get; set; }
public int i_parent { get; set; }
}
C# code : (objList has all the prefixes)
List<Prefixes> templist = new List<Prefixes>();
List<Prefixes> toAvoidList = new List<Prefixes>();
foreach (var item in objList.OrderByDescending(x => x.prefix.Length))
{
if (templist.Contains(item))
continue;
var temp = objList.Where(s => item.prefix.StartsWith(s.prefix)).ToList();
if (temp.Count > 0)
{
var lowerPricesPrefixes = temp.Where(x => x.price < item.price).Except(templist).ToList();
templist.AddRange(lowerPricesPrefixes);
}
else
{
templist.Add(item);
}
}
Please help and advise what could be optimized.
Thanks