trying to use linq aggregate function

612 Views Asked by At

I have below query where i am using the where clause with select and getting the result (list of librarySourceRowInputs) and would like to use the aggregate instead of (where and select).

In this process I am trying to access the same variables inside the aggregate but not getting any reference and below is the code for the same

public static LibrarySourceTableInput CreateLibrarySourceTableInput<T>(List<T> libraries, string mechanicalLibraryName)
       where T : ISourceOfData => new LibrarySourceTableInput()
{             
    LibrarySourceRowInputs = libraries?
                             .Where(l => l != null)
                             .Select(l => new LibrarySourceRowInput()
                             {
                                 LibrarySourceId = l.Id,
                                 SourceOfDataId = l.SourceOfData.Id
                             }).ToList() ?? new(),
    MappedLibrarySource = mechanicalLibraryName
};

below is the function where i am trying to use aggregate

// trying to replace the where and select in above with aggregate
 var LibrarySourceRowInputs = libraries.Aggregate(new List<LibrarySourceRowInput>(), 
 (prev, next) => 
        // here I am not getting any reference for Id
        );

I am not sure is this proper way to achieve this or any other way. Could any one please suggest any idea on this, many thanks in advance!

1

There are 1 best solutions below

2
Glory Raj On BEST ANSWER

I fix this issue by using aggregate like as below

 LibrarySourceRowInputs = libraries?.Aggregate(new List<LibrarySourceRowInput>(), 
 (acc, ids) =>
 {
     if (ids != null)
     {
         acc.Add(new LibrarySourceRowInput() { LibrarySourceId = ids.Id, 
                                               SourceOfDataId = ids.SourceOfData.Id });
     }
     return acc;
 })