如果列表为空,则添加默认字符串 [英] Adding a default string if list empty

查看:220
本文介绍了如果列表为空,则添加默认字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个状态汇总列表.除了没有的情况以外,它都可以正常工作.此刻,将呈现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(String.Empty, (a, b) => a + b)

现在,我想用" --- "填充表格元素,以防通过 Condition 将列表过滤为空列表,但是我可以还没有决定方法.

Now, I'd like to populate the table element with "---" in case the list is filtered down to an empty one by Condition but I can't decide on a method.

一种平滑的处理方式是什么?

What would be a smooth way to approach it?

我已经尝试过以下类似的暴行,但看起来……好极了,而且也无法正确渲染.我看到了实际的源代码行(以 False True 开头),而不是值.

I've tried something like the atrocity below but it looks, well..., atrociously and it doesn't render right, neither. I get to see the actual source code line (preceded by False or True) instead of the values.

item.Stuff.Where(e => Condition(e)).Count() < 1
  ? "---"
  : item.Stuff.Where(e => Condition(e))
    .Select(f => f.Status)
    .Aggregate(String.Empty, (a, b) => a + b)

推荐答案

您可以执行以下操作.如果状态列表相当小(否则应该使用 StringBuilder 而不是字符串连接).

You could do something like this. If the status list is reasonably small (otherwise one should use StringBuilder anyway and not string concatenation).

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

它检查是否替换了默认文本,如果已替换,则将下一个状态元素连接到已经存在的文本块中.

It checks if the default text was replaced and, if it was, it concatenates the next status element to the already existing text mass.

当且仅当它从未被评估过,即如果列表为空,它将返回" --- ".否则,将获得与以前相同的结果.

This will return "---" if and only if it's never evaluated, i.e. if the list is empty. Otherwise one would get the same result as previously.

如果Status是一个枚举,并且只需要不同的状态,则可以使用[Flags]属性的行为.

If Status is an enum, and you only need the distinct statuses, you can use the behavior of the [Flags] attribute.

如果您这样定义枚举

[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)

结果是列表中所有状态的集合,并且输出是格式正确的列表(Active, Inactive, Pending)或None(如果永不运行的话).

The result is a collection of all statuses that are present in the list, and the output is nicely formatted list (Active, Inactive, Pending) or None if it's never run.

这篇关于如果列表为空,则添加默认字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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