【问题标题】:Find all matches in a List LinQ查找列表中的所有匹配项 LinQ
【发布时间】:2015-02-27 11:28:22
【问题描述】:

鉴于这种情况,我从包含 ID 的文件中获得了一个字符串数组。
可以用各种字符分隔,“”:;等等
我想使用 LinQ 获取一个新列表/数组中的每个字符串,其中包含任何给定的分隔符。
我目前正在以一种相当不方便的方式这样做

string[] separator = { " ", ",", ";", ".", ":", "/" };
string[] arr = { };
listExceptions = someSource;
List<string> entrysWithSeparator=
(from s in listExceptions where (ContainsAny(s,separator) == true) select s).ToList(); 
//ContainsAny returns a bool, if any of the separators was found in the string
List<string> tmpExceptions = listExceptions.ToList();

foreach (string s in entrysWithSeparator)
{                
    arr = s.Split(separator, StringSplitOptions.RemoveEmptyEntries);
    tmpExceptions.AddRange(arr.ToList());
}
listExceptions = new string[listExceptions.Count()-1];
listExceptions = tmpExceptions.Distinct().ToArray();

【问题讨论】:

  • 为什么要在倒数第二行创建一个数组,只是为了覆盖最后一行变量的值?我发现很难遵循你想要实现的目标 - 一个具体的例子会很有用。
  • 如何显示可能的输入数据与预期数据
  • @JonSkeet 我假设您指的是最后两行。我有一些问题没有用一个新的数组覆盖现有的数组,那里有一些工件,我不知道如何在不创建新数组的情况下正确解决这个问题

标签: c# arrays linq list


【解决方案1】:

您应该能够使用SelectMany 组合查询和循环:

listExceptions = listExceptions
    .Where(s => ContainsAny(s,separator))
    .SelectMany(s => s.Split(separator, StringSplitOptions.RemoveEmptyEntries))
    .ToArray();

我假设您在查询中使用ContainsAny 方法similar to this one

【讨论】:

    【解决方案2】:
    var result = list.SelectMany(s => 
                    s.Split(separator, StringSplitOptions.RemoveEmptyEntries))
                 .Distinct();
    

    不需要 ContainsAny,因为不包含分隔符的字符串上的 Split() 也返回字符串本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多