我有這個代碼
Regex containsDelimitersInBrackets = new Regex(@"\[(.*?)\]");
foreach (Match match in containsDelimitersInBrackets.Matches(_sequence))
_separator.Add(match.Groups[1].Value);
我想使用 LINQ 將每個組的每個值添加到_separator串列中。
我試過這個。
_separator.AddRange(containsDelimitersInBrackets.Matches(_sequence).Where(x => x.Groups[1].Value));
但它不起作用。這樣做的正確方法是什么?
uj5u.com熱心網友回復:
Matches 可以回傳 1 個或多個 Matches,因此您可以使用 Select 從 Match(es) 中獲取組 1 值,然后使用 SelectMany 壓平該集合以分別獲取每個組的每個值。
然后您可以使用 addRange 將集合添加到_separator串列中。
例如
List<string> _separator = new List<string>(){"existing item"};
Regex containsDelimitersInBrackets = new Regex(@"\[([^][]*)]");
List<string> _sequence = new List<string>(){"test[1] test[2]", "test[123]"}
.SelectMany(s =>
containsDelimitersInBrackets.Matches(s)
.Select(m =>
m.Groups[1].Value
)
).ToList();
_separator.AddRange(_sequence);
_separator.ForEach(s => Console.WriteLine(s));
輸出
item one
1
2
123
請注意,除了非貪婪量詞之外,您還可以使用否定字符類來防止某些回溯。
Regex containsDelimitersInBrackets = new Regex(@"\[([^][]*)]");
請參閱C# 演示。
uj5u.com熱心網友回復:
你很接近..
我們不使用.Where將值 x(即Match物件)投影到值 y(即字串)中,我們使用.Select
_separator.AddRange(containsDelimitersInBrackets
.Matches(_sequence)
.Cast<Match>()
.Select(x => x.Groups[1].Value)
);
.Cast<T>()在使用老式 xxxCollection 類時,您還需要一個,以使 LINQ 可以輕松處理從其列舉器回傳的型別。否則編譯器會將其視為物件的列舉,并且您不會獲得非常有用的智能感知。(如果你寫,foreach(var m in someMatchCollection)那么m將是object.. 當你寫foreach(Match m in someMatchCollection)它時,它會從你宣告的方式中獲取型別提示m)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/380053.html
上一篇:無法將“System.Collections.Generic.List”型別的物件轉換為“System.Collections.Generic.ICollection”
下一篇:如何優化查詢-Efcore
