列出集合中所有实体的字段 [英] Listing a field from all the entities in a collection

查看:99
本文介绍了列出集合中所有实体的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写状态汇总列表。除了没有的情况以外,它都可以正常工作。此刻,将呈现null,位置为空。

I'm writing out an aggregated list of statuses. It works fine except for the situation where there are none. At the moment, null is rendered and the position is empty.

item.Stuff.Where(e => Condition(e))
  .Select(f => f.Status)
  .Aggregate("---", (a, b) => (a == "---") ? b : (a + b));

我有解决方案和改进建议如下。

[Flags]
enum Status
{
    None = 0,
    Active = 1,
    Inactive = 2,
    Pending = 4,
    Deleted = 8
}

item.Stuff.Where(e => Condition(e))
  .Aggregate(Status.None, (a, b) => a | b.Status)

我是非常喜欢简单语法的人,我喜欢跳过 Select 部分。但是,现在的结果不是列出的所有元素。实际上,只列出了一个(而不是以前的五个),并且 None 出现在以前只有一个状态的地方。

As I'm a great fan of simpler syntax, I love skipping the Select part. However, the result now is not all the elements listed. In fact, only a single one is listed (instead of five as previously) and None appears where there was a single status before.

也许我太不知所措了,但我不明白为什么。因此,这也不是我该怎么做,也不...:(

Perhaps I'm too brain-stuck but I can't see why. And, consequently, not what I should do about it, neither... :(

推荐答案

如果状态来自外部系统(即数据库),您可能还需要在那里重新编号状态。

If the statuses are coming from an extenal system (i.e. a database) you might need to renumber the statuses there as well.

请注意,仅当您使用二幂的值作为值时,此方法才有效

Note that this works only if you use power-of-two values as the values of the statuses.

例如,如果我使用

[Flags]
enum Status
{
    None = 0,
    Active = 1,
    Inactive = 2,
    Pending = 3,
    Deleted = 4
}

然后 Status.Active | Status.Inactive 将返回 Status.Pending (1 + 2 = 3)。

then Status.Active | Status.Inactive will return Status.Pending (1+2=3).

这样一来,您只会获得不同使用状态的列表,即,如果您有10个活动项和5个待处理项,您将获得活动,待处理作为结果,没有任何频率信息。

Also, this way you only get a list of distinct used statuses, i.e. if you have 10 active and 5 pending items, you'll get Active, Pending as a result, without any frequency information.

如果您也需要此信息,我建议进行一些分组,例如:

If you need this information too, I would suggest doing some grouping, like:

string.Join(", ", item.Stuff.Where(e => Condition(e))
  .Select(f => f.Status)
  .GroupBy(status => status)
  .Select(group => string.Format("{0} {1}", group.Count(), group.Key));

如果没有组,这将导致 10 Active,5 Pending或空字符串。

this will result in "10 Active, 5 Pending" or an empty string if there are no groups.

编辑:现在我想到了, string.Join 也许也可以更好地解决原始问题( IEnumerable.Aggregate 是一个很好的方法,但可能会过分杀伤)。就像这样:

Now I think of it, string.Join might be a better solution to the original question as well (IEnumerable.Aggregate is a great method, but it might be an overkill). Just something like:

string.Join(", ", item.Stuff.Where(e => Condition(e)).Select(f => f.Status))

这篇关于列出集合中所有实体的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆