从用户输入的字符串中创建字符串列表c#

时间:2015-06-02 22:06:03

标签: c# list

我有这个方法:

public List<string> AdvMultiKeySearch(string key)
{
    string[] listKeys = key.Split(',');

    string[] ORsplit;
    List<string> joinedDashKeys = new List<string>();
    List<string> joinedSearchKeys = new List<string>();

    for (int i = 0; i < listKeys.Length; i++)
    {
        ORsplit = listKeys[i].Split('|');
        joinedDashKeys.Add(string.Join(",", ORsplit));
    }

    for (int i = 0; i < joinedDashKeys.Count; i++)
    {
        string[] split = joinedDashKeys[i].Split(',');
        for (int j = 0; j < split.Length; j++)
        {
            joinedSearchKeys.Add(string.Join(",", split[i]));
        }
    }

    return joinedDashKeys;
}

我正在尝试创建一个接收字符串Keyword的方法,该字符串由单词,comas和'|'组成字符。例如,用户输入

  

谷氨酸| SAL,1368 | 1199

方法应该生成/返回字符串列表:"glu,1368", "glu,1199", "sal,1368", "sal,1199"

已经超过两个小时,我仍然无法弄清楚如何正确实现它。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

如果有上面的输入,只要有一个逗号就会显示任意数量的组合。

char[] splitter1 = new char[] { '|' };
char[] splitterComma = new char[] { ',' };
public List<string> AdvMultiKeySearch(string key)
{
    List<string> strings = new List<string>();

    string[] commaSplit = key.Split(splitterComma);
    string[] leftSideSplit = commaSplit[0].Split(splitter1);
    string[] rightSideSplit = commaSplit[1].Split(splitter1);

    for (int l = 0; l < leftSideSplit.Length; l++)
    {
        for (int r = 0; r < rightSideSplit.Length; r++)
        {
            strings.Add(leftSideSplit[l] + "," + rightSideSplit[r]);
        }
    }

    return strings;
}