Home > Net >  Join the data of different Lists present in different classes
Join the data of different Lists present in different classes

Time:12-06


public class EmpManagement
{
    public List<Employee> empList = new List<Employee>();

    //Method for adding new employee
    public void AddEmp(Employee emp)
    {
        empList.Add(emp);
    }

    public void displayEmp(Employee emp)
    {
        Console.WriteLine("["   emp.Empname   "]");
    }

    //Method for viewing all employees
    public void ShowEmp()
    {
        foreach (var e in empList)
        {
            displayEmp(e);
        }
    }
}


public class Role
{
    public string RoleName { get; set; }

    public Role(string roleName)
    {
        RoleName = roleName;
    }
}


public class RoleManagement
{
    public List<Role> RoleList = new List<Role>();

    //Method for adding roles
    public void RoleAdd(Role role)
    {
        RoleList.Add(role);
    }

    //Method for viewing all roles
    public void displayRole()
    {
        foreach (var e in RoleList)
        {
            Console.WriteLine(e.RoleName);
        }
    }
}

Join the above two lists in a different class

How can i add below two Lists into another list of different class

I am facing a problem while using a interface in one class and extending into the new class

I am also unable to use contains keyword, the compiler says that the name does not exist in current context

CodePudding user response:

You could not add two lists of different types in another single list. But you could still take casting into consideration and cast the two data types into a single data type and then perform the combination of the two lists into another single list. for more information, you could refer to the following :

https://linuxhint.com/csharp-combine-two-lists/#:~:text=We will demonstrate an example,cs” extension.

CodePudding user response:

First, declare two lists and join these two in another list. Please check the example below

List <string> list1 = new List <string>(){"L1L1","L1L2","L1L3"};
List <string> list2 = new List <string>(){"L2L1","L2L2","L2L3"};
List<string> joinList = list1.Join(list2);

Please see another example which is given below.

public class Role
{
   public string name { get; set; }
}

public class Role2
{
   public string name { get; set; }
}

public class RoleManagement
{
   public List<Role> r1 = new List<Role>();
   public List<Role> r2 = new List<Role>();

   List<string> joinList2 = r1.Join(r2);
}
  • Related