Using contains in linq - c#

I have a filtered list which returns all the distinctIds from MenuTable
var _parentList = _employee.Designation.Role.MenuRoles
.Select(x => new
{
MenuParentID = x.Menu.ParentID
})
.DistinctBy(x => x.MenuParentID)
.OrderBy(x => x.MenuParentID)
.ToList();
I want to select all the items from menutable which is in _parentList
This is what i have tried and an error is coming on _parentList.Contains(x.Id) which says Best overloaded match for System.Generic.contains has some invalid arguments.
MenuParentList = _db.Menus.Where(x => _parentList.Contains(x.Id))
.Select(x => new SMS.Models.ViewModel.DashboardVM.MenuParent
{
MenuParentID = x.Id,
MenuParentName = x.MenuName
})
.ToList()
Any help will be appreciated

Cf. this code:
.Select(x => new
{
MenuParentID = x.Menu.ParentID
})
This results in a list of anonymous objects with one property called MenuParentID, instead of a list of integers. The compiler creates a type for you that structurally looks like this (note that the compiler generates a non-usable class name behind the scenes instead of AnonymousType1, but you get the idea):
class AnonymousType1
{
public int MenuParentID {get;set;}
}
And _parentList would be of type List<AnonymousType1>.
Adjust your code as follows:
var _parentList = _employee.Designation.Role.MenuRoles
.Select(x => x.Menu.ParentID)
.Distinct()
.OrderBy(id => id)
.ToList();
Now _parentList is of type List<int>.
You can read more about the concept of anonymous types on msdn: https://msdn.microsoft.com/en-us/library/bb397696.aspx

Related

EF Dynamic Field Select using LINQ

I have the following select:
var sortedCodes = Codes
.Where(c => c.Active)
.OrderByDescending(x => x.SortOrder)
.Select(b => new { b.Display, b.NumericCode, b.SortOrder })
.Distinct()
.ToList();
The table Code has many columns such as NumericCode, TextCode, AlphaCode, ThreeCode, FourCode, FiveCode. I am using this table to build selects in my UI. Is there a way I can create some dynamic code so I can pass in the column name to use for the value?
The above select would look like this:
.Select(b => new { b.Display, "TextCode", b.SortOrder })
I was thinking I could use an Expression, but I do not think this is exactly what I need as it is actually printing the lambda as the value.
var arg = Expression.Parameter(typeof(Code), "b");
var body = Expression.Property(arg, valueColumn);
var lambda = Expression.Lambda<Func<Code, string>>(body, arg);
var sortedCodes = Codes
.Where(c => c.Active)
.OrderByDescending(x => x.SortOrder)
.Select(b => new { b.Display, Value=lambda, b.SortOrder })
.Distinct()
.ToList();

How to access the query fields in this LINQ?

I have the following function in my code and I need to access the "Source_Type_Id" and "Source_Type_Name". I don't have the option to create a class to hold these values.
public IList getalltblsource_type(string Source_Type_Name = "")
{
var query=db.tblsource_type
.Where(c => c.Source_Type_Name.Contains(Source_Type_Name))
.Select(c => new { c.Source_Type_Id, c.Source_Type_Name })
.OrderBy(c => c.Source_Type_Name)
.ToList();
return query;
}
I need to get query.Source_Type_Id and query.Source_Type_Name
From Jon Skeet and Dennis answers in comments. I used dynamic typing. Here's an example:
dynamic query=db.tblsource_type.Where(c => c.Source_Type_Name.Contains(Source_Type_Name)).Select(c => new { c.Source_Type_Id, c.Source_Type_Name }).OrderBy(c => c.Source_Type_Name).ToList();
int s = query.Source_Type_Id;

DbIsNullExpression exception in linq to EF4 query

I have writed linq EF4 query, but it failed with exception The argument to "DbIsNullExpression must refer to a primitive, enumeration or reference type." The query written bellow:
from listing in ctx.listingSource
join listingFile in ctx.ListingFiles
.Where(x => companyIds.Contains(x.CompanyID.Value))
.GroupBy(x => x.ListingID)
.Select(x => new { ListingId = x.Key, Count = x.Count() }) on listing.ListingID equals listingFile.ListingId into listingFilesJoined
from listingFileJoined in listingFilesJoined.DefaultIfEmpty()
select new ListingDTO
{
fileCount = listingFileJoined == null ? 0 : listingFileJoined.Count,
}
How can I resolve this issue without creating class instead anonymous type ?
fileCount = (int?)listingFileJoined.Count ?? 0
There are no way to select data without creating concrete type =\
There is fix bellow:
.Select(x => new ConcreteType { ListingId = x.Key, Count = x.Count() })
Maybe this answer help someone.

Cannot convert IQueryable<IEnumerable<string>> to return type IEnumerable<string>

In the following function I get an error when I try to return a value saying:
Cannot convert
System.Linq.IQueryable<System.Collections.Generic.IEnumerable<string>>
to return type System.Collections.Generic.IEnumerable<string>
public IEnumerable<string> GetModuleKindPropertyNames(long moduleKindId)
{
var configurationId = GetModuleKindPertypeConfigurationId(moduleKindId);
var propertyNames = _dbSis.ModuleKinds
.Where(t => t.PerTypeConfigurationId == configurationId)
.Select(x => x.PerTypeConfiguration.Properties
.Select(z => z.Name));
return propertyNames; //red line below property names
}
How can I solve this issue?
It looks like you want to select items from a collection within a collection and flatten the result into a single sequence.
Conceptually, something like:
If that's the case, you're looking for the SelectMany method:
var propertyNames = _dbSis.ModuleKinds
.Where(t => t.PerTypeConfigurationId == configurationId)
.SelectMany(x => x.PerTypeConfiguration.Properties)
.Select(z => z.Name);

Get NHibernate QueryOver .SelectList(x) from Function

Is there a way to get a list of members from a function that can be passed in to SelectList()?
So instead of doing this
var dtos = repository.QueryOver<MicrofilmExportProcessed>()
.SelectList(list => list
.Select(x => x.Member1).WithAlias(() => dto.Member1)
.Select(x => x.Member2).WithAlias(() => dto.Member2)
.Select(x => x.Member3).WithAlias(() => dto.Member3))
.List<MicrofilmExportProcessed>();
Doing something like this:
var dtos = repository.QueryOver<MicrofilmExportProcessed>()
.SelectList(getMembersFromFunc())
.List<MicrofilmExportProcessed>();
I tried creating method that returns the same type as the input parameter of the SelectList but it still tells me the input type is invalid. Not sure what I'm missing.
Something like
Func<QueryOverProjectionBuilder<InvoiceDto>, QueryOverProjectionBuilder<InvoiceDto>> GetList()
{
InvoiceDto dto = null;
return list => list.Select(w => w.Client).WithAlias(() => dto.Client);
}
and call it like
return Session.QueryOver<InvoiceDto>()
.SelectList(GetList())
.TransformUsing(Transformers.AliasToBean<InvoiceDto>())
.List<InvoiceDto>();

Categories