c# - 获取List <string>中字符串的索引

标签 c# linq

有没有更优雅的方法可以使用LINQ实现以下代码?
基本上,我想获取所有索引的列表,这些索引中一个列表中的字符串出现在另一个列表中。

private List<int> GetColumnIndexesToIgnore(
     ReadOnlyCollection<string> listOfColumnsToIgnore, List<string> columnHeadings)
{
    List<int> columnIndexesToIgnore = new List<int>();
    for (int i = 0; i < columnHeadings.Count; i++)
    {
        if (listOfColumnsToIgnore.Contains(columnHeadings[i]))
        {
            columnIndexesToIgnore.Add(i);
        }
    }
    return columnIndexesToIgnore;
}

最佳答案

您可以使用LINQ做到这一点:

var res = columnHeadings
    .Select((v, i) => new {Value = v, Index = i})
    .Where(p => listOfColumnsToIgnore.Contains(p.Value))
    .Select(p => p.Index)
    .ToList();


第一个Select对值及其索引进行配对,Where子句过滤掉不需要的对,第二个Select收集返回的索引,而ToList从其中删除List<int>

关于c# - 获取List <string>中字符串的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33226601/

相关文章:

c# - EWS Exchange Web 服务 API AutodiscoverUrl 异常

c# - 测试字典<k,v>中的一项

c# - 无法将类型 'System.Collections.Generic.List<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<Model.tblLaborBankAccount>'

c# - 使用正则表达式连接 linq

c# - 如何检查我的多线程代码是否确实在多个线程上运行?

C# 字典值引用类型 - 请解释为什么会这样

c# - 在 SQL Azure 中保存 XML 文件

c# - LINQ 对象 : How to join different properties in the same List of objects

c# - Linq DataTable 和 Take 方法

c# - 如何使用 LINQ 获取与条件总和匹配的属性?