[英]C# - Sort array of struct without using any built-in function, just using loops
I have a struct of employee data and it 2 separated fields of first name and last name. 我有一个员工数据结构,它由2个姓氏和名字分开的字段组成。 i want to sort this array by first name and in case of 2 names are the same then sort them by last name.
我想按名字对这个数组进行排序,如果2个名字相同,则按姓氏对它们进行排序。 I already sorted the array by the first name but still cant do it by the last name in case 2 first names are the same.
我已经按名字对数组进行了排序,但是在2个名字相同的情况下,仍然不能按姓氏对数组进行排序。 I want to implement this sort without using any built-in functions in .Net such as array.sort() i just want to use loops.
我想实现这种排序而不使用.Net中的任何内置函数,例如array.sort()我只想使用循环。
public struct EmployeeData
{
public char sex;
public int age;
public int id1;
public int id2;
public int id3;
public string fname;
public string lname;
public int seniority;
}
static EmployeeData[] SortByFirstName(EmployeeData[] empdata)
{
int min = 0;
EmployeeData temp;
for (int i = 0; i < empdata.Length; i++)
{
for (int j = i+1; j < empdata.Length; j++)
{
if (empdata[i].fname.Length < empdata[j].fname.Length)
{
min = empdata[i].fname.Length;
}
else
{
min = empdata[j].fname.Length;
}
for (int k = 0; k < min; k++)
{
if (empdata[i].fname[k] > empdata[j].fname[k])
{
temp = empdata[i];
empdata[i] = empdata[j];
empdata[j] = temp;
break;
}
else if (empdata[i].fname[k] == empdata[j].fname[k])
{
continue;
}
else
{
break;
}
}
}
}
return empdata;
}
Change your sort function to handle both first name and last name. 更改您的排序功能以处理名字和姓氏。
Where you say 你在哪里说
else if (empdata[i].fname[k] == empdata[j].fname[k])
{
continue;
}
Instead of continuing, sort the two entries by last name.. 不用继续,而是按姓氏对两个条目进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.