提高代码的性能

时间:2014-09-11 10:48:57

标签: c# arrays linq generics

要求:我有两个字符串数组。 empDetails数组包含四个字段,假设字段1是ID,其他字段是详细信息。 empToRemove数组包含要删除的员工的ID。创建不包含empToRomove数组中存在的ID的数组字符串。请注意我必须使用此代码,其中包含empDetails中的100000多个数据以及empToRemove中的20000多个数据。 任何建议都被挪用了。

string[] empDetails = { "1,abc,2,11k", "2,de,3,11k", "3,abc,2,18k", "4,abdc,2,12k" };

string[] empToRemove = { "1","3" };

我的解决方案

class Program
  {
    static void Main(string[] args)
    {
        string[] empDetails = { "1,abc,2,11k", "2,de,3,11k", "3,abc,2,18k", "4,abdc,2,12k" };

        string[] empToRemove = { "1","3" };

        //Add emp details in list of employee
        List<emp> e = new List<emp>();
        foreach (var item in empDetails)
        {
            Dictionary<int, string> tempEmployee = new Dictionary<int, string>();
            int i = 1;
            foreach (string details in item.Split(','))
            {
                tempEmployee.Add(i, details);
                i++;
            }
            e.Add(new emp { ID = int.Parse(tempEmployee[1]), Details1 = tempEmployee[2], Details2 = tempEmployee[3], Details3 = tempEmployee[4] });
        }
        foreach (string item in empToRemove)
        {
            emp employeeToRemove = e.Where(x => x.ID == int.Parse(item)).Single();
            e.Remove(employeeToRemove);
        }
        foreach (var item in e)
        {
            Console.WriteLine(item.ID + item.Details1 + item.Details2 + item.Details3);
        }
        Console.ReadLine();
    }
}
class emp
{
    public int ID { get; set; }
    public string Details1 { get; set; }
    public string Details2 { get; set; }
    public string Details3 { get; set; }
}

由于

2 个答案:

答案 0 :(得分:1)

如果我正确地理解了您的要求并且您唯一需要的是 - 打印(或操纵某些其他方式)empDetails的元素,这些元素ID不在empToRemove中 - 而不是您的代码完全矫枉过正。 以下将是足够的:

string[] empDetails = { "1,abc,2,11k", "2,de,3,11k", "3,abc,2,18k", "4,abdc,2,12k" };
string[] empToRemove = { "1", "3" };

var remove = new HashSet<string>(empToRemove);
foreach (var item in empDetails)
{
    string id = item.Substring(0, item.IndexOf(','));
    if (!remove.Contains(id))
        Console.WriteLine(item); // or your custom action with this item
}

答案 1 :(得分:0)

    string[] empDetails = { "1,abc,2,11k", "2,de,3,11k", "3,abc,2,18k", "4,abdc,2,12k" };
    string[] empToRemove = { "1","3" };

    foreach (string item in empToRemove)        
      empDetails = empDetails.Where(val => val.Substring(0, val.IndexOf(',')) != item).ToArray(); 

是单向的。不能比那更有效率吗?

基于以下研究:

How to delete an element from an array in C#