我跟踪了一系列字符串。每个字符串的默认值设置为string.Empty。这个数组由一个函数返回。现在,我只想打印那些不为空的索引。我可以用if有没有很短的方法让我只打印那些不为空的项目?
string [] muniSearches = {airSearchReport, certOfOccupancy, emerRepair, fire, fZone,foSearch, health, hsVoilation};发布于 2016-06-20 12:01:01
可以使用Select,如果值为null,则返回所提供的索引。
var indexesNotNull = muniSearches.Select((v, i) => new { Value = v, Index = i })
.Where(x => x.Value != null)
.Select(x => x.Index);或者简单地使用for循环:
List<int> indexesNotNull = new List<int>();
for (int index = 0; index < muniSearches.Length; index++)
{
if (muniSearches[index] != null)
{
indexesNotNull.Add(index);
}
}发布于 2016-06-20 12:21:54
我不清楚你是想要值还是索引。如果您想要值,并且可以在上下文中使用linq,这是相当直接的。
muniSearches
.Where(s => !string.IsNullOrEmpty(s))
.ToList()
.ForEach(Console.WriteLine);如果您想要索引,这也是可行的,但涉及更多。类似于:
muniSearches
.Select((s, i) => new {value = s, index = i})
.Where(o => !string.IsNullOrEmpty(o.value))
.Select(o => o.index)
.ToList()
.ForEach(Console.WriteLine);发布于 2016-06-21 10:09:31
您可以使用lambda表达式语法检查该字符串的长度,然后存储该字符串的索引,其中包含任何数据。
var Indexes = muniSearches.Select((Value, Index) => new { Value , Index })
.Where(x => x.Value.Length > 0)
.Select(x => x.Index);https://stackoverflow.com/questions/37922021
复制相似问题