-1

I have 2 string Lists. In the first List I have 30 or more entries. For the second list, I need to merge 3 items and add them to list 2 as 1 item.

Here an example of what I mean:

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
dinosaurs.Add("VelociRaptor")

List<string> dinosaursmerged = new List<string>();

Inside this list there are two items, which contain:

item1 = "Tyrannosaurus;  Amargasaurus; Mamenchisaurus"
item2 = "Mamenchisaurus; Mamenchisaurus; VelociRaptor"

I tried it with the stringbuilder and with concat but had no success. Any help or advice would be great - thanks for your time.

mc01
  • 3,750
  • 19
  • 24
opelhatza
  • 244
  • 1
  • 4
  • 19
  • 1
    Have you looked at [`string.Join`](https://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx)? – D Stanley May 24 '16 at 15:54
  • How are your items related? Do you always take groups of 3? – D Stanley May 24 '16 at 15:57
  • @DStanley yes string join makes one long string with the 30 items from the other list and adds it as one item. And yes always groups of 3. Sorry for the duplicate didnt showed up.... – opelhatza May 24 '16 at 15:59
  • @DStanley can i delete the question know or can i just ignore it? – opelhatza May 24 '16 at 16:08
  • You can delete if you want - it might get closed by a moderator, or merged into the duplicate, or just be left alone. – D Stanley May 24 '16 at 17:02

1 Answers1

0

If you want to group your first list in a second list with 3 elements joined together then you could write

List<string> merged = new List<string>();
for(int x = 0; x < dinosaurs.Count; x+=3)
    merged.Add(string.Join(",", dinosaurs.Skip(x).Take(3)));

This will work also if the first list doesn't contain a number of elements multiple of 3. Of course the last element could be composed of 1, 2 or 3 elements from the first list.

Steve
  • 213,761
  • 22
  • 232
  • 286