如何从列表中提取那些在c#
中具有方括号的元素例如。
list<string> lst=new List<string>(){ "ABC","[ABC]", "AB[c", "AB]C","ab 1" "12a", "ab1","[abc 1]", "12","15","[XYZ-12ac]","ab 1", "[233]" };
从上面我想创建列表,比如..
AlphaNumeric_List= {"AB[c", "AB]C", "12a", "ab1", "ab 1"}
OuterBrackets_List={"[XYZ-12ac]", "[233]","[ABC]"}
答案 0 :(得分:2)
foreach(string s in lst)
{
if(s.StartsWith("[") && s.EndsWith("]"))
{
//add to OuterBracket_List
OuterBracket_List.Add(s);
}
else
{
int n;
if (int.TryParse(s, out n) == false)
{
//add AlphaNumeric_List
AlphaNumeric_List.Add(s);
}
else
{
//add n to Numeric List
}
}
}
更新1 :
上面的代码处理用括号[]括起来的字母数字,数字和字符串。
更新2 :
此处的所有解决方案可能都包含12
中的15
,ABC
和AlphaNumeric_List
等数字值:
然而,只有字母类别也存在,但我已将您的列表区分为3类字符串:
enclosed in brackets
例如“[ABC]”containing Alpha-numeric
例如“ab 1”containing numeric characters
仅限ex。 12 这是更新的代码:
foreach (string s in lst)
{
if (s.StartsWith("[") && s.EndsWith("]"))
{
//add to OuterBracket_List
OuterBracket_List.Add(s);
}
else
{
int n;
if (int.TryParse(s, out n) == false && isAlphaNumeric(s))
{
//add AlphaNumeric_List
AlphaNumeric_List.Add(s);
}
else
{
//add n to Numeric List if required
}
}
}
//method to check string is AlphaNumeric Note: Regex can be used
public bool isAlphaNumeric(string strToCheck)
{
for (int i = 0; i < strToCheck.Length; i++)
{
if (char.IsLetter(strToCheck[i]) == false)
{
return true;
}
}
return false;
}
这是输入:
List<string> lst = new List<string>() { "ABC", "[ABC]", "AB[c", "AB]C",
"ab 1", "12a", "ab1", "[abc 1]",
"12", "15", "[XYZ-12ac]", "ab 1",
"[233]" };
这是输出:
OuterBracket_List = {"[ABC]", "[abc 1]", "[XYZ-12ac]", "[233]"}
AlphaNumeric_List = {"AB[c", "AB]C", "ab 1", "12a", "ab1", "ab 1"}
答案 1 :(得分:2)
试试这个
var OuterBrackets_List= lst.Where(s => s.StartsWith("[") && s.EndsWith("]");
var AlphaNumeric_List = lst.Except(OuterBrackets_List);
答案 2 :(得分:1)
使用StartsWith \ EndsWith(感谢musefan):
AlphaNumeric_List = list.Where(s => !(s.StartsWith("[") && s.EndsWith("]"))).ToList();
OuterBrackets_List = list.Where(s => (s.StartsWith("[") && s.EndsWith("]"))).ToList();
答案 3 :(得分:0)
如果您愿意使用LINQ,那么就这样......
//get list of values that are NOT wrapped in square brackets
List<string> AlphaNumeric_List - lst.Where(x => !x.StartsWith("[") || !x.EndsWith("]")).ToList();
//get list of values that ARE wrapped in square brackets
List<string> OuterBrackets_List = lst.Where(x => x.StartsWith("[") && x.EndsWith("]")).ToList();