简体   繁体   中英

Update List Concatanate string

I have a class

public class RoomAvail
{
    public int OCCUPANCY { get; set; }
    public int ChildCount { get; set; }
    public string ChildAges { get; set; }
}

I have List of RoomAvail ie List rooms;

rooms = { new RoomAvail{OCCUPANCY =1,ChildCount =1,ChildAges ="1" }
          new RoomAvail{OCCUPANCY =2,ChildCount =2,ChildAges ="1,2" }
          new RoomAvail{OCCUPANCY =3,ChildCount =3,ChildAges ="1,2,3" }
        }

I have populated the value of rooms.

I have List listAge = {12,13,14,14}

My requirement : if any OCCUPANCY in the list =2 , I should append the value of listAge in ChildAges .

Final Output:

rooms = { new RoomAvail{OCCUPANCY =1,ChildCount =1,ChildAges ="1" }
          new RoomAvail{OCCUPANCY =2,ChildCount =2,ChildAges ="1,2,12,13,14,15" }
          new RoomAvail{OCCUPANCY =3,ChildCount =3,ChildAges ="1,2,3" }
        }

I want to update rooms variable only.

I am doing:

rooms.Where(y => y.OCCUPANCY == 2)
     .Select(x => x.ChildAges)
     .Aggregate((i, j) => i + listAge  + j);

Thanks

LINQ doesn't modify your object(s). Use a loop for that

foreach(var room in rooms.Where(y => y.OCCUPANCY == 2))
{
    room.ChildAges = string.Join(",", room.ChildAges.Split(',').Concat(listAge));
}

You could try this one:

// Get the rooms with OCCUPANCY value equal to 2.
rooms = rooms.Where(x=>x.OCCUPANCY==2);

// Iterate through the selected rooms.
foreach(var room in rooms)
{
    // Build a list of integers based on the room's list age.
    List<int> currentListAge = room.ChildAges.Split(',').Select(int.Parse).ToList();

    // Concat the currentListAge with the listAge, order the resulting list and
    // then build a comma separated value list.
    room.ChildAges = String.Join(",", currentListAge.Concat(listAge)
                                                    .OrderBy(x=>x)
                                                    .Select(x=>x.ToString())
                                                    .ToList());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM