I've searched for a solution on SO but I couldn't find it, so I've made this new question.
I have 2 list of two different classes.
First class:
public class Class1
{
public int C1Property1 {get;set;}
public int C1Property2 {get;set;}
public int C1Property3 {get;set;}
}
And second class:
public class Class2
{
public int C2Property1 {get;set;}
public int C2Property2 {get;set;}
public int C2Property3 {get;set;}
}
And I have two list of those classes:
List<Class1> Class1List = new List<Class1>();
List<Class2> Class2List = new List<Class2>();
Now comes the hard part for me: Two of those properties in both classes have the same value, but with a different name: i.e. C1Property1 = C2Property1
and C1Property2 = C2Property2
. The list Class1List
has the property C1Property1
which is empty, and I need to populate it using the property from Class2List
. I do this by using the following code:
foreach(var element1 in Class1List)
{
foreach(var element2 in Class2List)
{
if(element2.C2Property2 == element1.C1Property2)
{
element1.C1Property1 = element2.C2Property1;
}
}
}
This solution works how I intent it, but is very ugly and I have 2 foreach-loops which can be slow (list can contain over 10 000 elements). In the example classes I wrote only 3 properties to show how it works, but originally it has ~20 properties each, and only 2 of them are the same. Can I do this faster and more efficient? Some LinQ perhaps? I can't show more code, sorry. I hope that you will understand what I'm asking.
I need to take only one property from Class2List
and place it on Class1List
only when one of parameters in list are same.
In my second attempt i use something like that :
foreach (var element1 in Class1List)
{
foreach (var element2 in Class2List.Where(element2 => element2.C2Property2 == element1.C1Property2 ))
{
element2.C2Property2 = element1.C1Property2;
break;
}
}
This should be faster but still look ugly