简体   繁体   English

如果列表为空,则添加默认字符串

[英]Adding a default string if list empty

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. 此刻,将呈现null且该位置为空。

item.Stuff.Where(e => Condition(e))
  .Select(f => f.Status)
  .Aggregate(String.Empty, (a, b) => a + b)

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. 现在,我想用“ --- ”填充表格元素,以防列表被Condition筛选成一个空的列表,但我无法决定使用哪种方法。

What would be a smooth way to approach it? 有什么流畅的方法可以解决呢?

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. 我可以看到实际的源代码行(以FalseTrue开头 )而不是值。

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)

You could do something like this. 你可以做这样的事情。 If the status list is reasonably small (otherwise one should use StringBuilder anyway and not string concatenation). 如果状态列表相当小(否则应该使用StringBuilder而不是字符串连接)。

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, ie if the list is empty. 当且仅当它从未被评估过,即列表为空时,才会返回“ -- ”。 Otherwise one would get the same result as previously. 否则,将获得与以前相同的结果。


If Status is an enum, and you only need the distinct statuses, you can use the behavior of the [Flags] attribute. 如果Status是一个枚举,并且只需要不同的状态,则可以使用[Flags]属性的行为。

If you define the enum like this 如果您这样定义枚举

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

you can just do: 您可以这样做:

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

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. 结果是列表中存在的所有状态的集合,并且输出是格式正确的列表( Active, Inactive, Pending )或None如果从不运行)。

You can use DefaultIfEmpty(string.Empty).First(); 您可以使用DefaultIfEmpty(string.Empty).First(); MSDN MSDN

Example

var item =  item.Stuff.Where(e => Condition(e))
  .Select(f => f.Status)
  .Aggregate(String.Empty, (a, b) => a + b);

var newitem = item.DefaultIfEmpty(new Item() { i = 1, Status = "---" }).First();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM