Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have one main list:

List<object1> LIST1
object1 have properties: Id, Name
and
List<object2> LIST2
object2 with properties: Id, Name

I wanna try from linq to add from list2 data to list1 to have one flat list with both data...I try by lame way to get that but i want from linq...

What I have tried:

C#
foreach (item in list.selectmenu(a => a.list2).toList())
{
//blalballala
}
Posted
Updated 12-Jun-18 11:57am
v2
Comments
F-ES Sitecore 12-Jun-18 5:09am    
I don't really understand your question but the solution is probably AddRange and possibly SelectMany. AddRange lets you add a list of items to a list;

list1.AddRange(list2.Where(x => x.Prop = 123))

SelectMany turns a list of lists into a single list, if you can understand that :)

You can only do that if object2 is derived from object1 - otherwise you are trying to insert two different type objects into the same list.
You can do it quite easily if they are related:
class Fruit { }
class Apple : Fruit { }
class Banana : Fruit { }
class SampleClass
    {
    public static void Main()
        {

        List<Fruit> fruits = new List<Fruit>() { new Apple(), new Apple() };
        List<Banana> bananas = new List<Banana>() { new Banana(), new Banana() };
        fruits.AddRange(bananas);

        }
    }
But without some relationship between them, you can only combine them into a List of a class from which they both inherit.
 
Share this answer
 
Comments
Maciej Los 12-Jun-18 7:12am    
5ed!
Member 11381811 12-Jun-18 8:05am    
Tnx for adviced i solve my problem ... you are the best...
OriginalGriff 12-Jun-18 8:22am    
You're welcome!

You could use a Mapper. A Mapper maps one Type to another Type where the property names are the same, the other Type must have a default constructor. A popular Mapper is AutoMapper the one used here is a home-brewed version but the syntax is similar.


C#
List<Animal> animals = new List<Animal>
           {
               new Animal(){Name="Dog",Legs=4},
               new Animal(){Name="Human",Legs=2},
               new Animal(){Name="Spider",Legs=8}

           };
           List<Animal2> animals2 = new List<Animal2>
           {
              new Animal2(){Name="Insect",Legs=6},
               new Animal2(){Name="Fish",Legs=0}

           };
           //     source   target
           Mapper<Animal2, Animal> myMapper=new Mapper<Animal2, Animal>();
           var query = animals2.Select(a => myMapper.Map(a));
           animals.AddRange(query);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900