c# - Using LINQ, how would you filter out all but one item of a particular criteria from a list? -
i realize title isn't clear here's example:
i have list of objects 2 properties, , b.
public class item { public int { get; set; } public int b { get; set; } } var list = new list<item> { new item() { = 0, b = 0 }, new item() { = 0, b = 1 }, new item() { = 1, b = 0 }, new item() { = 2, b = 0 }, new item() { = 2, b = 1 }, new item() { = 2, b = 2 }, new item() { = 3, b = 0 }, new item() { = 3, b = 1 }, }
using linq, what's elegant way collapse = 2 items first = 2 item , return along other items? expected result.
var list = new list<item> { new item() { = 0, b = 0 }, new item() { = 0, b = 1 }, new item() { = 1, b = 0 }, new item() { = 2, b = 0 }, new item() { = 3, b = 0 }, new item() { = 3, b = 1 }, }
i'm not linq expert , have "manual" solution expressiveness of linq , curious see if done better.
how about:
var collapsed = list.groupby(i => i.a) .selectmany(g => g.key == 2 ? g.take(1) : g);
the idea first group them a
, select again (flattening .selectmany
) in case of key
being 1 want collapse, take first entry take(1)
.
Comments
Post a Comment