【发布时间】:2014-03-27 13:58:36
【问题描述】:
我在这里看到了一个类似的问题,有一个很好的解决方案: Simplest way to form a union of two lists
但这里的问题是,当每个列表中只有一个参数(int 值)时,它可以工作。我有这个要求来组合 5 个不同的列表,其中包含同一类的对象,没有数据冗余,最终列表应该按 int 值的升序排序。
例子:
Class Company //data Class
{
int companyNo;
string Name;
}
Class CompanyList : List<Company>
{
.................
public CompanyList GetList(int userID)
{
.....
}
}
class company 有一个公共方法返回与搜索条件相对应的公司列表,让我们使用 userID。
CompanyList list1 = CompanyList .GetList(userID1);
CompanyList list2 = CompanyList .GetList(userID2);
CompanyList list3 = CompanyList .GetList(userID3);
CompanyList list4 = CompanyList .GetList(userID4);
CompanyList list5 = CompanyList .GetList(userID5);
The solution I implemented is (worked well):
CompanyList _finalList = list1;
*foreach (CompanyList _list in {_list2 ,_list3 ,_list4 ,_list5}) //loop thorugh all other list
{
foreach (Company item in _list)
{
for (int i = 0; i <= _finalList.Count - 1; i++)
{
if (_finalList.Item(i).CompanyNo== item.CompanyNo)
//***EXIT TAKE NEXT LIST - GO TO *
}
if (i == _finalList.Count - 1) //else check end of first list
{
//company no. not yet encountered(new)
int pos = 0;
foreach (Company companyInfo in _finalList) //search for position for new company no.
{
if (companyInfo.CompanyNo> item.CompanyNo)
{
break;
}
else
{
pos = pos + 1; //increment position
}
}
_finalList.Insert(pos, item); 'Add new item
}
}
}
**代码从 VB.Net 转换为 C#。在这里我找不到此行的等效代码段,因此将其替换为概念。
我不是专业的 C# 程序员,只是想知道是否有更好或更简单的方法来做到这一点?
数据示例:
Input:
list1[0] = {0,"TCS"};
list1[1] = {1,"Infosys"};
list2[0] = {8,"IBM"};
list3[1] = {1,"Infosys"};
list4[0] = {0,"TCS"};
list5[0] = {9,"Accenture"};
list5[1] = {6,"HCL"};
Output:
finalList[0] = {0,"TCS"};
finalList[1] = {1,"Infosys"};
finalList[2] = {6,"HCL"};
finalList[3] = {8,"IBM"};
finalList[4] = {9,"Accenture"};
问候 sj
【问题讨论】:
标签: c# vb.net visual-studio-2010 for-loop foreach