在asp.net中有条件地绑定下拉列表

时间:2017-06-03 18:19:26

标签: c# asp.net arrays list asp.net-2.0

我有一个特殊格式的字符串

string LogInIDs = 124,345, 876 | 765,322, 98 | 565,99

字符串中的所有数字都是唯一登录ID。使用Pipe符号,分组由id完成。现在,假设 LogInID 345 ,那么我需要绑定其他数字(在这种情况下 124 & 876 )在下拉列表中的组中。以下功能是我检索其他数字的功能。

任何人都可以提出任何更好的想法或建议

public static List<string> RetrieveAffCodes(string LogInIDs , string LogInID)
{
    List<string> _finale = new List<string>();

    string[] sep1 = new string[1];
    sep1[0] = "|";

    int count = LogInIDs.Count(x => x == '|');
    string[] groups = new string[count + 1];
    groups = LogInIDs.Split(sep1, StringSplitOptions.RemoveEmptyEntries);

    foreach (string g in groups)
    {
        string p = g;
        string[] sep2 = new string[1];
        sep2[0] = ",";
        int counter = p.Count(x => x == ',');
        string[] final_list = new string[counter + 1];
        final_list = p.Split(sep2, StringSplitOptions.RemoveEmptyEntries);

        foreach (string _f in final_list)
        {
            if (_f.Trim() == LogInID)
            {
          _finale =  AddLogInIDs(final_list, final_list.Count());
            }
        }
    }
    return _finale;
}

private static List<string> AddLogInIDs(string[] final_list, int p)
{
    List<string> _finale = new List<string>();
    foreach (var item in final_list)
    {
        _finale.Add(item.Trim());
    }
    return _finale;
}

任何建议都会被接受。

感谢您的时间和耐心。

  

注意:该字符串最多可扩展到200个组

2 个答案:

答案 0 :(得分:0)

试试这个..

    public static List<string> RetrieveAffCodes(string logInIDs, string logInID)
    {
        return logInIDs
        .Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
        .Where(a => a.Split(',').Any(c => c.Trim().Equals(logInID)))
        .Select(a => a.Split(',').ToList()).FirstOrDefault();
    }

答案 1 :(得分:0)

这对你有用吗?

using System;
using System.Collections.Generic;           
using System.Linq;

public class Program
{
    public static void Main()
    {
        string LogInIDs = "124,345,876|765,322,98 |565,99";

        Console.WriteLine(string.Join("\n", RetrieveAffCodes(LogInIDs, "322")));
        Console.WriteLine(string.Join("\n", RetrieveAffCodes(LogInIDs, "565")));
    }

    public static IEnumerable<string> RetrieveAffCodes(string logInIDs , string logInID)
    {
        //We split the list
        var list = logInIDs.Split('|');
        //We look for an item with the logInID, if found (?) we split using ',' and then we remove the item
        var match = list
            .Select(i => i.Split(',').Select(item => item.Trim()))
            .FirstOrDefault(i => i.Contains(logInID))?
            .Where(i => i != logInID);

        if(match != null)
        {
            return match;
        }

        return new List<string>();

    }
}

源代码:https://dotnetfiddle.net/M2FyNk