Reuse LINQ select function

Reuse LINQ select function

By : oysteinheimark
Date : November 22 2020, 10:38 AM
it should still fix some issue Try storing the Func in a variable, and re-use it. Something like this:
code :
internal static IQueryable<UserModel> SelectUser(this IQueryable<User> query, bool getChildren) {
    log.DebugFormat("create the select statement for an individual user {0}", getChildren ? "with children" : "without children");

    var res = query.Select(u => new UserModel {
        // [...] unimportant stuff
        Groups = u.Groups.AsQueryable().Select(MyLinqExpressions.fSelect).Take(10),
        CreatedGroups = !getChildren ? null : u.CreatedGroups.AsQueryable().Select(MyLinqExpressions.fSelect).Take(10)
        // [...] more stuff like above just different types
    return res;
public static class MyLinqExpressions {
    public static Func<Group,GroupModel>
        fSelect = g => new GroupModel {
            Name = g.Name,
            Description = g.Description,
            ID = g.ID

Share : facebook icon twitter icon
How to reuse part of Linq to Entity Select expression in EF4.1 code only scenario

How to reuse part of Linq to Entity Select expression in EF4.1 code only scenario

By : user3163693
Date : March 29 2020, 07:55 AM
should help you out I would create a new class CLASSNAME that has two properties
PrintJobReportItem type GROUPING IEnumerable>
code :
public static IQueryable<CLASSNAME> EXTENSIONNAME<TKey, TSource>(this IEnumerable<IGrouping<TKey, TSource>> source)
  return from g in source
         select new CLASSNAME
           PrintJobReportItem = new PrintJobReportItem
                                  TotalPagesPrinted = g.Sum(p => p.PagesPrinted),
                                  AveragePagesPrinted = etc...,
                                  PercentOfSinglePagePrintJobs = etc...,
           GROUPING = g
var q1 = repo.GetQuery<PrintJob>()
    .GroupBy(pj => pj.UserName)
    .Select(g => new PrintJobByDepartmenReportItem
                    PrintJobReportItem = g.PrintJobReportItem,
                    DepartmentName = g.GROUPING.Key,
                    NumberOfUsers = g.GROUPING.Select(u => u.UserName).Distinct().Count()

Is it possible to reuse parts of a LINQ to Entities select statement?

Is it possible to reuse parts of a LINQ to Entities select statement?

By : Hetty
Date : March 29 2020, 07:55 AM
this will help
As an alternative to Func<>s, you can also make use of extension methods to reuse the conversions between your entity types to and other POCOs.
code :
public static IQueryable<CustomerDevice> ToCustomerDevice(this IQueryable<PTT_CUSTOMER_DEVICES> devices)
    return devices.Select(d => new CustomerDevice
        customerAssetTag = d.CustomerAssetTag,
        customerDeviceID = d.CustomerDeviceID
public static Model ToModel(this PTS_MODELS model)
    return new Model()
        ModelID = model.ModelID,
        Name = model.Name,
        Make = new Make()
            MakeID = model.PTS_MAKES.MakeID,
            Name = model.PTS_MAKES.Name

public static IEnumerable<CustomerDevice> ToCustomerDevice(this IQueryable<PTT_CUSTOMER_DEVICES> devices)
    return devices
        .Include(d => d.PTS_MODELS.PTS_MAKES)
        .AsEnumerable() // Evaulate everything that follows in memory
        .Select(d => new CustomerDevice
            customerAssetTag = d.CustomerAssetTag,
            customerDeviceID = d.CustomerDeviceID,
            Model = d.PTS_MODELS.ToModel()
Reuse select new object in linq statement

Reuse select new object in linq statement

By : mttyice
Date : March 29 2020, 07:55 AM
wish helps you Below is my linq code and it works. My question is how I can "reuse" those part new ContactResponse, and new AddressResponse in a function to reuse it in another query? , If I correct understand your question, then try this:
code :
 Func<WorkshopContact, ContactResponse> contactResponseProjection= p => new ContactResponse
   Id = p.Contact.Id,
   Type = p.Contact.ContactType.Description,
   Code = p.Contact.ContactType.Code,
   Value = p.Contact.Value
  Contacts = a.WorkshopContacts.Select(contactResponseProjection).ToList(),

Why can't I reuse a function in LINQ to SQL

Why can't I reuse a function in LINQ to SQL

By : user3837691
Date : March 29 2020, 07:55 AM
I wish did fix the issue. In the second snippet, the logic is being translated into a lambda expression which is then compiled into an expression tree... the two query translations are:
How to reuse LINQ Select Expression with arguments

How to reuse LINQ Select Expression with arguments

By : z l
Date : March 29 2020, 07:55 AM
I hope this helps . Rather than having a field that stores the expression, have a method that creates the expression that you need given a particular string:
Related Posts Related Posts :
  • Accessing Settings in different ways
  • "This project is empty" error in Sonarqube
  • How to create reusable icon menu in Xamarin
  • Value Cannot be null in Ado.Net connectivity
  • Adding a custom/dynamic attribute when using XSD.exe
  • How to convert object to correct type
  • Automatically sign out from Forms Authentication in ASP.NET when browser is closed
  • Can a WCF service support both Buffered and Streamed transfer modes?
  • Verify a CA Certificate with a public key in C#
  • How to invoke a Web Service that requires the "patch" verb using the C# WebClient wrapper?
  • Proper way a implementing property based on generic type
  • Closing a form that is created in another thread
  • How Can You Bind a List<String> to a StackPanel
  • WPF Application Update Best Practices - Architectural Explanation
  • System.UnauthorizedAccessException in Server.MapPath()
  • Connecting and Using SQL Compact Edition in a WPF application
  • C#: weird ref in constructor to behave like "virtual field"
  • C# XDocument Load with multiple roots
  • How to decide what goes in the Domain or Application Project in a "DDD" solution?
  • How to get/set a property of an interface that is not always implemented
  • Read-only array field in unsafe struct
  • i got "Invalid attempt to call Read when reader is closed" when using sqldatareader how to solve it in a three
  • Why should I encapsulate objects in using if there is garbage collection
  • How to load Word document from byte array
  • Caliburn.Micro and ContextMenu for DataGrid Row
  • Linq "join" with a IList<T> getting "Error Unable to create a constant value.."
  • How to draw red wavy line under words in RichTextBox c# winform
  • HttpPostedFileBase returns Null MVC3
  • Refresh Dropdownlist in webform
  • How to convert serialized byte array back to its text form
  • How to do a loop to check all the variables at the same time for C#?
  • Facebook Sentiment Analysis API
  • Counting occurrences of specific letters in string
  • Module 'System.Data.Linq' Version=, Culture=neutral, Publickeytoken=b77a5c561934e089' should be referenced
  • C# MVC Dynamically create view model
  • Get Executing Path of C# application when using nunit with Jenkins
  • GDI count stable near 100 but Handle count keep increasing
  • Problem adding string value to ViewBag from an MVC Action using TempData
  • Reading Excel file on condition
  • what is windows programming from C++, C# and Java perspective?
  • How to deal with C# object references in MongoDB?
  • How to create a list from filtering 2 lists with linq to object
  • Webclient calls to DownloadString cause my app to freeze
  • How to create a JSON WebService in c# ASP.Net with a valid JSON output and query with JQuery/Ajax
  • Submit button not working as expected
  • MvcSitemapProvider parameters sometimes works sometimes not
  • Console application doesn't obey Thread.Join
  • System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
  • Creating a scripting environment for a C# program
  • Is it reasonable to replace .Equals with a method rather than override it?
  • How I can capture multiple keys?
  • How to have all my classes default functionalities like .ToString method
  • Business Object properties: model as Objects or Enums?
  • Loading this assembly would produce a different grant set from other instances
  • How to call a method without first calling it's constructor in C#
  • Can't set a date time in one of my entity framework objects, says NullReferenceException
  • GETJob() Win32 Print spooler api 64bit The parameter is incorrect, how to fix?
  • Switch Case Causing Trouble In Going To A particular Function
  • Switch Case Calling A Function Based On The User's Choice
  • Accessing WebBrowser on different Threads
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org