在多维字符串数组中搜索字符串模式[,]

时间:2015-11-04 17:13:25

标签: c# arrays string c#-4.0 multidimensional-array

假设我有多维对象数组,表示员工信息,例如

String[,] Employee= new object[,] { 
             {"john","MBA#MBA#BE#MBA#BE"},
             {"jan","MS#MSC#MBA"},

};

可视化

 john                 MBA#MBA#BE#MBA#BE    
 jan                   MS#MSC#MBA

我想删除重复的数据(数据除以#)

 john                 MBA#BE   
 jan                  MS#MSC#MBA

2 个答案:

答案 0 :(得分:1)

对于这种情况,最好使用字典:

Dictionary<string, string> employee = new Dictionary<string, string>()
{
    {"john", "MBA#MBA#BE#MBA#BE"},
    {"jan", "MS#MSC#MBA"}
}

Dictionary<string, string> result = new Dictionary<string, string>();

foreach (var kvp in employee)
{
    result[kvp.Key] = string.Join("#", kvp.Value.Split('#').Distinct());
}

result字典将包含结果:

// Prints "MS#MSC#MBA"
Console.WriteLine(result["jan"]);

// Prints "MBA#BE"
Console.WriteLine(result["john"]);

答案 1 :(得分:0)

就个人而言,我会创建一个类来保存该信息

public class Employee
{
    public Employee(string name)
    {
        Name = name;
        Degress = new HashSet<string>();
    }

    public string Name { get; private set; }
    public HashSet<string> Degrees { get; private set; }
}

然后你可以像这样填写一个列表

string[,] employeeArray = { { "john", "MBA#MBA#BE#MBA#BE" }, { "jan", "MS#MSC#MBA" } };

List<Employee> employees = new List<Employee>();

for (int i = 0; i < employeeArray.GetLength(0); i++)
{
    Employee employee = new Employee(employeeArray[i,0]);
    foreach (var degree in employeeArray[i, 1].Split('#'))
    {
        employee.Degrees.Add(degree);
    }

    employees.Add(employee);
}

foreach (var e in employees)
{
    Console.WriteLine(e.Name + " " + string.Join(" ", e.Degress));
}

打印

  

john MBA BE

     

MS MS MBA

由于DegreesHashSet,因此不允许重复,当您尝试将副本传递给Add时,它只会返回false