【问题标题】:c#: New string array from two, where one has strings the other contains?c#:来自两个的新字符串数组,其中一个包含字符串,另一个包含?
【发布时间】:2013-11-26 23:03:32
【问题描述】:

我有两个字符串列表。

1:

new List<string>{ "jan", "feb", "nov" }

2:

new List<string>{ "these are the months", "this is jan,", "this is feb,", "this is mar,",  "this is jun,", "this is nov"}

我希望我的结果是:

List<string>{ "these are the months", "this is jan,", "this is feb,", "this is nov"}

现在我正在做一个混乱的拆分,然后是一个包含 linq 和一个嵌套的 foreach。

但是必须有一个更简单的方法,我想到了一个 linq left JOIN,左边有列表 2,但不知道如何实现它,如果这甚至是正确的方法。

有什么想法吗?

谢谢。

【问题讨论】:

  • 不能直接根据第一个列表的内容生成结果列表吗?

标签: c# string linq list merge


【解决方案1】:

你可以用一点 Linq 做到这一点:

var list1 = new List<string>{ "jan", "feb", "nov" };
var list2 = new List<string>{ "these are the months", ... };

var result = list2.Where(x => list1.Any(y => x.Contains(y))).ToList();

但是,此结果集将不包含第一个元素,因为"these are the months" 不包含list1 中的任何字符串。如果这是一项要求,您可能需要执行以下操作:

var result = list2.Take(1).Concat(list2.Skip(1).Where(x => list1.Any(y => x.Contains(y)))).ToList();

【讨论】:

  • 感谢您的快速回复。但是,如果“包含”前面有多个字符串,而现在还不知道很多呢?再次感谢!
  • @user1013388 那么你怎么知道哪些需要包含在结果集中呢?
  • 你第一种方式选择的那些,没有顶部,然后与原始合并。我认为会做到的。
  • @user1013388 但我的问题是,如果它可以变化,你怎么知道“顶部”部分中有多少元素?如果你显示你现在拥有的foreach-loop,也许我就能理解其中的逻辑。
  • @user1013388 抱歉,但这仍然无济于事。在任何情况下,如果您可以确定“顶部”中有 n 元素,您可以使用我的代码并将我的代码中的 1 替换为 n
猜你喜欢
  • 1970-01-01
  • 2012-11-21
  • 2017-12-24
  • 2020-07-19
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多