![](/img/trans.png)
[英]Get all possible values from a string array that contains two strings 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.