C# Lists in Lists – Getting all inner values, or the unique inner values

Getting the inner value of a list inside a list can seem complicated in C#, but LINQ makes it easier. But first let’s make a list in a class, and then make a list of the class with the list of classes – you get the drift:

using System;
using System.Collections.Generic;
using System.Linq;

public class OuterClass 
{
	public IEnumerable<InnerClass> InnerClasses { get; set; }
}

public class InnerClass
{
	public string InnerValue { get; set; }	
}

Then let’s make a list of the OuterClass, and assign some values:

// The starting point: A list of OuterClasses
List<OuterClass> outerClasses = new List<OuterClass>();

// Make a list of InnerClasses, and add 3 values, A,B,C
List<InnerClass> innerClasses = new List<InnerClass>();
innerClasses.Add(new InnerClass() { InnerValue = "A" });
innerClasses.Add(new InnerClass() { InnerValue = "B" });
innerClasses.Add(new InnerClass() { InnerValue = "C" });

// Add a OuterClasses, each with a list of 3 InnerClasses
outerClasses.Add(new OuterClass() { InnerClasses = innerClasses });
outerClasses.Add(new OuterClass() { InnerClasses = innerClasses });
outerClasses.Add(new OuterClass() { InnerClasses = innerC

Now we have a list of 3 OuterClasses, and each OuterClass have a list of 3 InnerClasses, a total of 9 items, and a list of InnerValue like this: A,B,C,A,B,C,A,B,C

THE NON-LINQ WAY:

Without LINQ, you should make 2 loops:

foreach (var outerClass in outerClasses)
{
	foreach (var innerClass in innerClasses)
	{
		Console.WriteLine(innerClass.InnerValue);	
	}
}

This returns A,B,C,A,B,C,A,B,C

THE LINQ WAY:

Use the SelectMany to get all InnerClasses:

var allInnerClasses = outerClasses.SelectMany(o => o.InnerClasses);
foreach (var innerClass in allInnerClasses)
{
	Console.WriteLine(innerClass.InnerValue);	
}

This also returns A,B,C,A,B,C,A,B,C

GETTING ONLY THE UNIQUE VALUES:

To return only the unique values, do this:

var allUniqueInnerValues = outerClasses.SelectMany(o => o.InnerClasses)
	.GroupBy(i => i.InnerValue)
	.Select(i => i.First())
	.Select(i => i.InnerValue);
	
foreach (var innerValue in allUniqueInnerValues)
{
	Console.WriteLine(innerValue);
}

This will return only A,B,C.

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.