I'd use
.GroupBy()
on the checkedItems list, grouping on the
Value
.
Then I'd use a
.Select()
to traverse the groups, using
.Aggregate()
on each group, with a
StringBuilder
as the accumulator for
.Aggregate()
to construct the resulting parenthesized string of
Text
.
Finally, use
string.Join(" and ", ...)
to assemble it all in one string.
Where the
...
is the result of
.ToArray()
applied to the result of the
.Select()
.
I tried this example:
public class TestItem
{
public string Text;
public string Value;
public TestItem(string text, string value)
{
Text = text;
Value = value;
}
}
List<TestItem> test = new List<TestItem>();
test.Add(new TestItem("One", "Numeric"));
test.Add(new TestItem("Two", "Numeric"));
test.Add(new TestItem("Three", "Numeric"));
test.Add(new TestItem("A", "Character"));
test.Add(new TestItem("B", "Character"));
test.Add(new TestItem("C", "Character"));
test.Add(new TestItem("D", "Character"));
test.Add(new TestItem("#", "SplChar"));
test.Add(new TestItem("$", "SplChar"));
test.Add(new TestItem("%", "SplChar"));
var pieces = test.GroupBy(item => item.Value)
.Select(g => g.Skip(1).Aggregate(new StringBuilder(g.Key).AppendFormat(" in ('{0}'",g.First().Text),
(sb, item) => sb.AppendFormat(",'{0}'", item.Text),
sb => sb.Append(")").ToString()));
Console.WriteLine(string.Join(" and ", pieces.ToArray()));