Reputation: 155
I have a list of Field objects, with a parameter of (string)Name and (int)Size.
I also have a list of File objects, each containing a list of Field objects, in which some of them may appear in the overarching Field objects.
I need to go through all the Field objects, and find the max value of all possible File-Field objects.
I could do this with nesting 3? for loops, but I wanted to see if this is possible in linq.
List<fieldobject> mainfields;
List<fileobject> files;
within the fileobject class:
List<fieldobject> fields;
Basic concept in for loops would be:
foreach (fieldobject field in mainfields)
foreach (fileobject file in files)
foreach (fieldobject fileField in file.fields)
if (field.name == fileField.name)
field.size = math.max(field.size,fileField.size);
I can replace that if and assignment with a linq, but I was hoping to get rid of most/all of the for loops. Any help is greatly appreciated.
Upvotes: 0
Views: 1601
Reputation: 5986
If i understand correctly file.fields
is an internal list of fileobject inside fileobject object so you need to use the SelectMany
extension method:
foreach (fileobject field in mainfields)
{
field.size = files.SelectMany(x => x.fields)
.Where(y => y.name == field.name).Select(m => m.size).Max();
}
Upvotes: 1
Reputation: 4971
You could have something like;
foreach (fieldobject field in mainfields)
{
int maxFileSize = files.Where(f => f.name == field.name)
.Select(f => f.size)
.Max();
if (field.size < maxFileSize)
{
field.size = maxFileSize;
}
}
Upvotes: 0