Reputation: 151
I have Code where i have two Class called ClassA and ClassB and i have two fileds class in Number and Status in both the classes ,
I have created a two List called listA and listB,
I need to query it such that Only the Status
Property has to be transfer from listB to listA using linq / lambda expression.
How can i do that??
Thanks in Advance,
Here is my code snippet
class ClassA
{
public int Number { get; set; }
public bool Status { get; set; }
}
class ClassB
{
public int Number { get; set; }
public bool Status { get; set; }
}
static void Main(string[] args)
{
List<ClassA> listA = new List<ClassA> ();
List<ClassB> listB = new List<ClassB>();
ClassA a = new ClassA();
a.Number = 1; a.Status = false;
ClassA a2 = new ClassA();
a2.Number = 1; a2.Status = true;
ClassA a3 = new ClassA();
a3.Number = 1; a3.Status = true;
ClassA a4 = new ClassA();
a4.Number = 1; a4.Status = true;
ClassB b1 = new ClassB();
b1.Number = 2;b1.Status = true;
ClassB b2 = new ClassB();
b2.Number = 3; b2.Status = false;
ClassB b3 = new ClassB();
b3.Number = 2; b3.Status = true;
ClassB b4 = new ClassB();
b4.Number = 3; b4.Status = false;
listA.Add(a);
listA.Add(a2);
listA.Add(a3);
listA.Add(a4);
listB.Add(b1);
listB.Add(b2);
listB.Add(b3);
listB.Add(b4);
}
Upvotes: 0
Views: 110
Reputation: 101
try this following code:
static void Main(string[] args)
{
List<ClassA> listA = new List<ClassA> ();
List<ClassB> listB = new List<ClassB>();
ClassA a = new ClassA();
a.Number = 1; a.Status = false;
ClassA a2 = new ClassA();
a2.Number = 1; a2.Status = true;
ClassA a3 = new ClassA();
a3.Number = 1; a3.Status = true;
ClassA a4 = new ClassA();
a4.Number = 1; a4.Status = true;
ClassB b1 = new ClassB();
b1.Number = 2;b1.Status = true;
ClassB b2 = new ClassB();
b2.Number = 3; b2.Status = false;
ClassB b3 = new ClassB();
b3.Number = 2; b3.Status = true;
ClassB b4 = new ClassB();
b4.Number = 3; b4.Status = false;
listA.Add(a);
listA.Add(a2);
listA.Add(a3);
listA.Add(a4);
listB.Add(b1);
listB.Add(b2);
listB.Add(b3);
listB.Add(b4);
listA.AddRange(listB.Select(o => new ClassA() { Status = o.Status }));
}
Upvotes: 0
Reputation: 3009
I would use Automapper to map the two classes together in one call. This type of situation is what it was designed for. All you would need to do is create a mapping configuration and then map the two classes. It's a very simple but powerful tool. e.g. Something like this:
var config = new MapperConfiguration(cfg => cfg.CreateMap<ClassA, ClassB>()
);
var mapper = config.CreateMapper();
List<ClassA> listA = new List<ClassA>();
var listClassB = mapper.Map<List<ClassB>>(listA);
Upvotes: 2