Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - IQueryable query how to select? [duplicate]

IQueryable<ImportNameValidation> query = entities.ImportNameValidation
    .Where(y => y.FirstName == searchedName)
    .Where(x => x.NameType == comboValue);

List<ImportNameValidation> ResultValues = query.ToList();  

In this query, I get back 6 columns but I only need 3 of them, how can I use the select method to get only those columns that I need? is it something like

.Select(t => t.FirstName, u => u.Name, i => i.NameCode);

what I really want in SQL is instead of "select *" I want to "select NameCode, Name, FirstName" but I need that as an IQueryable.

like image 396
Ibrahim Aweidah Avatar asked Dec 11 '25 17:12

Ibrahim Aweidah


1 Answers

To select specific columns you need to project to an object with those properties (anonymous or custom)

.Select(t => new { t.FirstName, t.Name, t.NameCode })

In addition you can put the two where conditions in the same predicate:

entities.ImportNameValidation
        .Where(y => y.FirstName == searchedName && y.NameType == comboValue)
        .Select(t => new { t.FirstName, t.Name, t.NameCode })    

Or in query syntax:

from item in entities.ImportNameValidation
where item.FirstName == searchedName && item.NameType == comboValue   
select new { item.FirstName, item.Name, item.NameCode }

As the items in the collections are no longer of type ImportNameValidation you cannot assign this to a List<ImportNameValidation>. To do so project to a custom DTO object that contains there 3 properties (you cannot project to the mapped type - will cause an error):

List<ImportNameValidationDTO> result = entities.ImportNameValidation
    .Where(y => y.FirstName == searchedName && y.NameType == comboValue)
    .Select(t => new ImportNameValidationDTO { t.FirstName, t.Name, t.NameCode })
    .ToList();
like image 177
Gilad Green Avatar answered Dec 13 '25 05:12

Gilad Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!