Check the grouping of values ββin List <string>
In one of my programs, I need to check the grouping of items in a list. So I have values ββin List<string>
. Here's an example of a list (in that order):
Women
's
Women
's Women 's Women 's
Women
's
Men
's
Men
's Men 's Men 's Women's
What I want to check is the grouping of this list. So the women downstairs shouldn't be there. This is the wrong grouping.
I CANNOT sort this list because there will be a special order for it, which is not simple as in the above list (and can have more than two different values) and always changes. However, grouping will be supported.
All I want to do is find the wrong grouping and display the error. I hope there is a better way to do this than to loop like crazy. Thank!
source to share
You should do this by traversing the elements and keeping track of the unique elements seen in HashSet<string>
and the previous value.
string previous = items.FirstOrDefault();
var seen = new HashSet<string>();
seen.Add(previous);
for (int i = 1; i < items.Count; i++)
{
if (previous != items[i])
{
if (!seen.Add(items[i]))
{
Console.WriteLine("This item is not grouped:" + items[i] + " at index " + i);
}
previous = items[i];
}
}
source to share
foreach (string item in list.Distinct())
{
int startIndex = list.IndexOf(item);
int endIndex = list.LastIndexOf(item);
bool notGrouped = Enumerable.Range(startIndex, endIndex - startIndex + 1).Select(index => list[index]).Any(i => i != item);
if (notGrouped)
{
// show message for the current item
}
}
source to share