I saw a similar question here with a very good solutions: Simplest way to form a union of two lists
But the problem here is, it works when there is only one parameter in each list (int value). I had this rquirement to combine 5 different lists containing objects of the same class without data redundancy and the final list should be sorted out in ascending order of int value.
Example:
Class Company //data Class
{
int companyNo;
string Name;
}
Class CompanyList : List<Company>
{
.................
public CompanyList GetList(int userID)
{
.....
}
}
Class company has a pulic method returning list of companies corresponding to a search criteria, let us 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
}
}
}
**the code is converted from VB.Net to C#. Here I could not find the quivalent code piece for this line so replaced it with the concept.
I am not an expert C# programmer and just wondering if there is any better or simpler way to do this?
Data example:
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"};
Regards Sj