提高代码的性能
本文关键字:性能 代码 高代码 | 更新日期: 2023-09-27 18:21:40
要求:我有两个字符串数组。empDetails数组包含四个字段,假设字段一是ID,其他字段是details。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; }
}
感谢
如果我正确理解了您的需求,并且您唯一需要的是打印(或以其他方式操作)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
}
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();
是一种方式。不能变得比这更有效吗?
基于的研究
如何在C#中从数组中删除元素