I've got an ICollection<SomeClass>
.
public class SomeClass
{
public string Text { get; set; }
public bool IsPreferred { get; set; }
}
The items in there have been pre-ordered, so "next" does mean something.
In my scenario, the contents of the sequence looks like this:
[0] - "a", false
[1] - "b", true
[2] - "c", false
I'm trying to get the "next" element after the one that IsPreferred == true
. So in the above, i want to get element 2, and i want to clear the other IsPreferred
value.
So i want to end up with this:
[0] - "a", false
[1] - "b", false
[2] - "c", true
Basically shuffling the preferred item down.
What's the best way to do it? The only thing i can think of is to create a new array, add them one by one, keep track of the index of the one that is preferred, then go grab the element at the aforementioned index +1.
Any better ideas?
Since ICollection<T>
doesn't give you an indexer I would opt for a more direct solution rather than rely on LINQ.
Assuming you want to (1) stop as soon as the condition is met, and (2) only change the value if the next item exists, this can be achieved as follows:
bool isFound = false;
SomeClass targetItem = null;
foreach (var item in list)
{
if (isFound)
{
item.IsPreferred = true;
targetItem.IsPreferred = false;
break;
}
if (item.IsPreferred)
{
targetItem = item;
isFound = true;
}
}