仅打印C#中非空的字符串数组的索引

时间:2016-06-20 11:59:00

标签: c# arrays

我跟随数组字符串。每个字符串的默认值设置为string.Empty。这个数组由一个函数返回。现在,我想只打印那些非null的索引。我可以为每个索引使用if-else,但是通过8个项目可能会有很长的路要走。是否有任何简短的方法,以便我只能打印那些不是nulll的项目

string [] muniSearches = {airSearchReport, certOfOccupancy, emerRepair, fire, fZone,foSearch, health, hsVoilation};

3 个答案:

答案 0 :(得分:4)

如果值为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);
    }
}

答案 1 :(得分:1)

我不清楚你是否想要价值观或指数。 如果你想要值,你可以在上下文中使用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);

答案 2 :(得分:0)

您可以使用lambda表达式语法检查该字符串的长度,然后存储包含任何数据的字符串的索引。

var Indexes = muniSearches.Select((Value, Index) => new { Value , Index })
                             .Where(x => x.Value.Length > 0)
                             .Select(x => x.Index);