簡體   English   中英

c#:兩個新的字符串數組,其中一個包含另一個包含的字符串?

[英]c#: New string array from two, where one has strings the other contains?

我有兩個字符串列表。

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"}

現在我正在做一個混亂的分裂,然后一個包含帶有嵌套foreach的linq。

但是必須有一個更簡單的方法,我想到了一個linq左邊的列表2左邊的JOIN,也許,但不知道如何把它拉下來,如果這甚至是正確的方法。

有任何想法嗎?

謝謝。

你可以用一點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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM