Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter List<string> based on only a Substring

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:

  • The first three characters are filler
  • The 4th-6th characters refer to the group the SKU belongs to
  • The 7th-9th characters refer to the priority a SKU has within its respective group
  • The remaining 10th and so on characters are filler

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?

like image 598
JasonG Avatar asked Jun 14 '26 00:06

JasonG


1 Answers

The processing should go as follows:

  • Identify SKU groups in the list
  • Attach each SKU to its respective group
  • Order SKUs within each group by priority
  • Pick the top item in each group
  • Make a flat list from grouped result

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.

like image 77
Sergey Kalinichenko Avatar answered Jun 16 '26 14:06

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!