使用Linq搜索字符串列表 [英] Searching in a list of string using Linq
问题描述
大家好,
我有一个字符串列表.我必须以这种方式匹配列表中的字符数组,使得列表中的字符串必须仅包含数组中的字符.
例如:如果我的字符数组(下面代码中的_currentLetters字符串)是abdfuwz.那么从列表中选择的字符串的可能列表将是错误的,DAB等.
以下是我拥有的一种可能的解决方案:
Hello everyone,
I have a list of strings. I have to match a character array in the list in such a way that the strings in list must contain only characters in the array.
For ex: if my character array (_currentLetters string in the code below) is abdfuwz. Then the possible list of selected strings from the list would be bad, dab etc.
Below is one possible solution I have:
public string[] GetPossibleWords()
{
wordsList.Clear();
IEnumerable<string> words = from w in _list.WordListCollection
where (w.Length > 1 &&
w.IndexOfAny(_currentLetters.ToArray()) >= 0 &&
w.Length <= _currentLetters.Length)
select w;
// Check the sorted array of current letters. If the string
// is a substring of this, then the word is in
foreach (string s in words)
{
char[] toMatch = s.ToCharArray();
Array.Sort(toMatch);
string m = new string(toMatch);
if (_currentLetters.Contains(m))
{
wordsList.Add(s);
}
}
return wordsList.ToArray();
}
如您所见,我正在单词列表中搜索单词.获得单词列表后,我将再次使用找到的所有单词进行迭代,并确保找到的单词是字符数组的子字符串.此字符数组是字符的排序数组.我不确定这是否是实现我的目标的最佳方法.有没有更好的办法?我可以使用Linq编写整个代码吗?
谢谢
As you can see, I am searching words in my list of words. Once I get the word list, I am iterating again with all the words we found and making sure that the found word is a substring of the character array. This character array is a sorted array of characters. I am not sure if this is the best way to achieve my goal. Is there a better way? Can I write the entire code using Linq?
Thanks
推荐答案
最好像下面这样使用RegEx,
Hi,
Its better to use RegEx as like the below one,
class Program
{
static void Main(string[] args)
{
List<string> listOfPossibleStrings = GetStringsWithPossibleChars("abdfuwz",
new List<string>()
{
"jagan",
"bad",
"dad",
"well",
"test"
});
}
private static List<string> GetStringsWithPossibleChars(string pattern,List<string> lstStrings)
{
var newList = from str in lstStrings
where (new Regex(@"^[\s\d" + pattern + "]*
",RegexOptions.Singleline).IsMatch(str)== 选择 str; 返回(列表< string>)newList; } }
", RegexOptions.Singleline).IsMatch(str)== true) select str; return (List<string>)newList; } }
这篇关于使用Linq搜索字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!