Flatten List in LINQ
Try SelectMany()
var result = iList.SelectMany( i => i );
How to flatten list of lists?
Use SelectMany
:
var legalEntityIds =
query.SelectMany(x => x.LegalEntities).Select(y => y.LegalEntityId).ToList();
or, using query syntax:
var legalEntityIds = (
from item in query
from legalEntity in item
select legalEntity.LegalEntityId
).ToList();
Flatten a list which one of its properties is another list of object
You should use SelectMany to flatten a sequence of Main objects:
Projects each element of a sequence to an IEnumerable and flattens
the resulting sequences into one sequence.
So it projects each Main object into sequence of FlatList
objects and then flattens resulting sequences into one FlatList
sequence
var flatList = mainList.SelectMany(m =>
m.Owners.Select(o =>
new FlatList {
Id = m.Id,
Name = m.Name,
OwnerId = o.Id,
OwnerName = o.Name
})).ToList()
C# flatten a list of objects with a list property
We can try GroupBy
and SelectMany
:
List<Person> People = ...
var result = People
.GroupBy(person => new {
person.Name,
person.Age
})
.Select(chunk => new Person() {
Name = chunk.Key.Name,
Age = chunk.Key.Age,
Interests = chunk
.SelectMany(item => item.Interests)
.Distinct()
.ToList()
})
.ToList(); // if we want List<People>
How to group a list using linq c#
Try this:
var q = Data.Where(b => b.GroupID != null).GroupBy((x) => x.GroupID).Select((y) => new
{
GroupID = y.First().ID,
Name = string.Join(",", y.Select((k) => k.Name).Distinct()),
Type = string.Join(",", y.Select(( k) => k.Type).Distinct()),
Location = string.Join(",", y.Select(( k) => k.Location).Distinct()),
});
If you want to load the columns dynamically,use this code:
var q2 = Data.Where(b => b.GroupID != null).GroupBy((x) => x.GroupID).Select((y) => new
{
GroupID = y.First().ID,
result = DynamicGroup(y)
});
private static string DynamicGroup(IGrouping<string,DataD> y)
{
string result=null;
foreach (System.Reflection.PropertyInfo pInfo in typeof(DataD).GetProperties().Where(x=>x.Name!="GroupID" && x.Name!="ID"))
{
result += string.Format(" {0} ; ",string.Join(",", y.Select((k) => pInfo.GetValue(k, null)).Distinct()));
}
return result;
}
Flattening a list of lists, using LINQ, to get a list of parent/child
Thanks to the comments on my initial post, I was able to get what I was looking for.
The solution only works on one level, which is what I needed. It could be made recursive to go deeper though:
var result = parents.SelectMany(person => person.Children
.Prepend(person))
.Select(p => p.Name);
Gave me the expected result:
parentA
childB
childC
parentD
childE
childF
Which then allowed me to use all the objects in the flattened lists, including the parent objects.
Use Linq to flatten a nested list instead of a foreach loop
You can use SelectMany
, just concat the single parent and it's children:
List<SiloNode> newList = masterList.SelectMany(n => new[]{ n }.Concat(n.Children)).ToList();
Linq Flatten List of List
You use SelectMany
to flatten a list of lists:
var final = data.SelectMany(
student => student.Scores,
(student, score) => new FinalDto {
StudentID = student.StudentID,
ExamID = score.ExamID,
Mark = score.Mark
}
);
Console.WriteLine("StudentID, ExamID, Mark");
foreach (var result in final)
{
Console.WriteLine("{0}, {1}, {2}", result.StudentID, result.ExamID, result.Mark);
}
Alternatively, you can use a different overload of SelectMany
along with a nested Select
projection:
var final = data.SelectMany(
student => student.Scores.Select(
score => new FinalDto {
StudentID = student.StudentID,
ExamID = score.ExamID,
Mark = score.Mark
}
)
);
You can also use query syntax:
var final = (
from student in data
from score in student.Scores
select new FinalDto {
StudentID = student.StudentID,
ExamID = score.ExamID,
Mark = score.Mark
}
);
Note that this is just translated to the second form shown above.
There's no "best" here. Forms two and three literally compile to the same exact code. Form one is just a slight variation. There is no impact (speed, memory) for choosing one over the other. Pick the one that is visually appealing to you. Personally I don't write query syntax (the last form) and I always forget the first overload exists so I end up using the second one.
LINQ - flatten list of objects with child list into one list
You can use SelectManay
to flatten list of list of KeyValuePair<string, string>
to one list, like the following code :
List<KeyValuePair<string, string>> keyValuePairs = activities
.SelectMany(x => x.Users.Select(y => new KeyValuePair<string, string>(x.Number, y.Name)))
.ToList();
If you want list of KeyValuePair<string, User>
, use the following code:
List<KeyValuePair<string, User>> keyValuePairs = activities
.SelectMany(x => x.Users.Select(y => new KeyValuePair<string, User>(x.Number, y)))
.ToList();
Note that, Number
of activities considered unique.
Number
and Name
must be a string
.
i hope this will help you out.
How can I flatten out a list that contains another list using LINQ?
You can use the SelectMany
method to flatten multiple lists into a single list. In this case, you could do something like this:
var items = dictionary.GetEntries()
.SelectMany(x => x.Kanjis)
.Select(x => x.Text)
Related Topics
Data Binding to Selecteditem in a Wpf Treeview
Serialport Not Receiving Any Data
When Should I Use Double Instead of Decimal
Decimal Precision and Scale in Ef Code First
Using Async/Await For Multiple Tasks
How to Start a Process as Administrator Mode in C#
How to Have an Auto Incrementing Version Number (Visual Studio)
.Net Global Exception Handler in Console Application
C# Catch a Stack Overflow Exception
How to Rethrow an Exception in C#
Simple Proof That Guid Is Not Unique
Compare Two List≪T≫ Objects For Equality, Ignoring Order
How to Automatically Increment the File Build Version When Using Visual Studio