I have a list of SKUs (product numbers) and need to sort it based on a very specific criteria.
A list of SKUs, for example:
List<string> skuList = new List<string>()
{
"SKU001040AA",
"SKU003010DED",
"SKU002010VEVW",
"SKU003040EEGE",
"SKU001020GEF"
};
Each SKU is structured in a fashion as follows:
As such, the first SKU in the list belongs to group 001 and has a priority of 040. A lower numeric value has a higher priority. In which case, 030 is higher priority than 040. My goal here is to filter the list so that only the highest priority SKUs within their respective groups are kept. Using the above list for reference, a filtered list would contain "SKU003010DED", "SKU002010VEVW" and "SKU001020GEF". The filtered list does not need to be ordered. It will ultimately be packed into a JSON object and be sent away.
I have tried a few different approaches, several of which seemed to be very inefficient. It occurred to me that I could use the present format of the SKUs to order the list easily. After that, I thought it would be possible to use the Contains() method to check if a substring existed, but naturally that only works for complete strings within the list...
skuList = skuList.OrderBy(x => x).ToList();
List<string> skuListFiltered = new List<string>();
foreach (var sku in skuList)
{
//Unsure of the best approach to view substrings of skuList
if (!skuList.Contains(sku.Substring(3,3)))
{
skuListFiltered.Add(sku);
}
}
Is there any way to filter this list in such a fashion, or should I try an entirely different approach?
The processing should go as follows:
Here is how you do it with LINQ:
var topPriority = skuList
.GroupBy(sku => sku.Substring(3, 3))
.Select(g => g.OrderBy(sku => sku.Substring(6, 3)).First())
.ToList();
Note that since priorities are zero-padded, they have the same length of 3 characters. Hence, lexicographical ordering is the same as numerical ordering.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With