如何使用 LINQ 从多列列表中获取 x 行
我有一个看起来像这样的列表:
catId itemId value
1 5 "some text"
1 19 "some text"
1 21 "some text"
2 6 "some text"
2 8 "some text"
3 9 "some text"
3 82 "some text"
注意 catId
列。我如何为第一列中的每个唯一值获取 2 行(或删除额外的行)。 catId=1
仅 2 行 catId=2
2 行,依此类推?
我的列表名为 distinctXSelling
,我目前使用它的方式如下:
foreach (var item in distinctXSelling)
{
xSelling.InnerHtml += item.value;
}
I have a list that looks something like this:
catId itemId value
1 5 "some text"
1 19 "some text"
1 21 "some text"
2 6 "some text"
2 8 "some text"
3 9 "some text"
3 82 "some text"
Notice the catId
column. How would I take 2 rows(or remove extra rows) for each unique value in the first colum. Only 2 rows for catId=1
2 rows for catId=2
and so on?
My list is called distinctXSelling
and I'm using it like this currently:
foreach (var item in distinctXSelling)
{
xSelling.InnerHtml += item.value;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以按类别 ID 对项目进行分组,然后从每个组中选取前两个项目,然后将组序列展平为源项目序列。这看起来像:
请注意
Take
方法接受最多一定数量的项目,因此如果类别只有一个项目,则不会抛出异常。正如 BrokenGlass 指出的那样,如果您希望按特定顺序过滤出项目,则可能需要
.OrderBy
(也可能需要.ThenBy
)。您可能还需要考虑将循环替换为:
You can group items by their category-id and then pick the first two items from each group, before flattening the sequence of groups into a sequence of source-items. This would look like:
Note that the
Take
method takes upto a certain number of items, so this won't throw if a category has only a single item.As BrokenGlass points out, you might need a
.OrderBy
(and possibly a.ThenBy
) if you want the filtered items out in a specific order.You might also want to consider replacing the loop with:
如果您只是想将集合过滤到特定列,请使用
Where()
如果您想按所有列进行分组,请使用
Group()
If you're just looking to filter the set to a specific column, use
Where()
If you want to group by all of them, use
Group()