AmandaSai98b
AmandaSai98b

Reputation: 505

How to replace swap 2 properties for each instance inside a generic List?

How can I swap 2 properties from each instance inside a generic Lists. Explaining better:

I would like that BInstance1 become BInstance2 and BInstance2 become BInstance1 for all instances of A inside that List:

I am pretty sure I should be use Select linq extension method but I don't quite see the syntax for that

public class A
{
    public B BInstance1 { get; set; }
    public B BInstance2 { get; set; }
}

public class B
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Created { get; set; }
}


        var aList = new List<A>();

        aList.Add(new A()
        {
            BInstance1 = new B() { Created = DateTime.Now.Add(new TimeSpan(1, 0, 0, 0)), Id = 1, Name = "B1" },
            BInstance2 = new B() { Created = DateTime.Now.Add(new TimeSpan(2, 0, 0, 0)), Id = 2, Name = "B2" }
        });

        aList.Add(new A()
        {
            BInstance1 = new B() { Created = DateTime.Now.Add(new TimeSpan(3, 0, 0, 0)), Id = 3, Name = "B3" },
            BInstance2 = new B() { Created = DateTime.Now.Add(new TimeSpan(4, 0, 0, 0)), Id = 4, Name = "B4" }
        });

Upvotes: 0

Views: 105

Answers (1)

TheGeneral
TheGeneral

Reputation: 81493

If you wanted to encapsulate this logic as part of the class. Then you could do something like this

public class A
{
   public B BInstance1 { get; set; }
   public B BInstance2 { get; set; }

   // deconstruction tuple swap
   public void Swap() => (BInstance1, BInstance2) = (BInstance2, BInstance1);
}

Usage

var aList = new List<A>();

aList.Add(new A()
{
  BInstance1 = new B() { Created = DateTime.Now.Add(new TimeSpan(1, 0, 0, 0)), Id = 1, Name = "B1" },
  BInstance2 = new B() { Created = DateTime.Now.Add(new TimeSpan(2, 0, 0, 0)), Id = 2, Name = "B2" }
});

foreach (var item in aList)
  item.Swap();

Note : Obviously this doesn't need to part of a class, it could be an extension method, and helper method, or any other variation such as being used in line

Note 2 : If you wanted a new allocated list and clone of the original object you will need to project (Select) and manually (or by other means) recrate the objects individually

Upvotes: 1

Related Questions