【问题标题】:Exclude list items that contain values from another list排除包含另一个列表中的值的列表项
【发布时间】:2012-06-29 18:29:39
【问题描述】:

有两个列表:

List<string> excluded = new List<string>() { ".pdf", ".jpg" };
List<string> dataset = new List<string>() {"valid string", "invalid string.pdf", "invalid string2.jpg","valid string 2.xml" };

如何从“数据集”列表中过滤掉包含“排除”列表中的任何关键字的值?

【问题讨论】:

  • 正如 abatishchev 所说,将 excluded 设为 HashSet&lt;string&gt;,尤其是在它很大的情况下。
  • 谢谢。如果我们在 HashSets,我会给出这个链接来讨论这个主题:stackoverflow.com/questions/1247442/…

标签: c# .net linq filtering


【解决方案1】:
var results = dataset.Where(i => !excluded.Any(e => i.Contains(e)));

【讨论】:

  • 在列表中找不到包含?
  • @Choco: 使用 System.Linq;
  • 我使用 system.Linq 添加但它不知道排除
【解决方案2】:
// Contains four values.
int[] values1 = { 1, 2, 3, 4 };

// Contains three values (1 and 2 also found in values1).
int[] values2 = { 1, 2, 5 };

// Remove all values2 from values1.
var result = values1.Except(values2);

https://www.dotnetperls.com/except

【讨论】:

    【解决方案3】:

    试试:

    var result = from s in dataset
                 from e in excluded 
                 where !s.Contains(e)
                 select e;
    

    【讨论】:

      【解决方案4】:
      var result=dataset.Where(x=>!excluded.Exists(y=>x.Contains(y)));
      

      当排除列表为空时,这也有效。

      【讨论】:

        【解决方案5】:

        var result = dataset.Where(x => !excluded.Contains(x));

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-15
          相关资源
          最近更新 更多