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;
Related
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();
I still don't have a good grasp on LINQ yet, and felt like my code could be optimised so looking for help.
I have a Patient and Med Class, each have a public bool IsSelected. These are wrapped into the PatientMeds and PatientsMeds Classes;
public class PatientMeds
{
public Patient Patient;
public List<Med> Meds;
}
public class PatientsMeds
{
public List<PatientMeds> PatientMedsList;
}
I want to filter these, so if the Patient.IsSelected == false then ignore it, and ignore only the Meds where IsSelected == false;
Now, this code works:
List<PatientMeds> patientMedsList = PatientsMeds.PatientMedsList
.Where(x => x.Patient.IsSelected)
.ToList();
foreach (PatientMeds patientMeds in patientMedsList)
{
var medsToRemove = patientMeds.Meds.Where(m => m.IsSelected == false).ToList();
foreach (Med med in medsToRemove)
{
patientMeds.Meds.Remove(med);
}
}
But it just seems 'clunky'. How can i make it better?
I would use ForEach RemoveAll method
List<PatientMeds> patientMedsList = PatientsMeds.PatientMedsList
.Where(x => x.Patient.IsSelected)
.ToList();
patientMedsList.ForEach(p=> p.Meds.RemoveAll(m=>!m.IsSelected));
You could construct a new list with new PatientMeds instances containing only selected patients and meds:
var selectedPatientsWithSelectedMeds = patientMedsList.Where(p => p.IsSelected)
.Select(p => new PatientMeds
{
Patient = p.Patient,
Meds = p.Meds.Where(m => m.IsSelected).ToList()
})
.ToList();
So the Where(p => p.IsSelected) only selects selected patients, and the Select(p => new PatientMeds { ... } constructs new PatientMeds instances.
Finally p.Meds.Where(m => m.IsSelected).ToList() constructs a new list with only selected meds.
But it's not clear whether constructing new PatientMeds and List<Med> instances is viable. For example at new PatientMeds { ... } you will need to map all properties of PatientMeds.
Try shortening the following foreach loop
foreach (PatientMeds patientMeds in patientMedsList)
{
patientMeds.Meds.RemoveAll(m => m.IsSelected == false);
}
You can try RemoveAll
patientsMeds
.PatientMedsList
.Where(m => m.Patient.IsSelected)
.ToList()
.ForEach(m => m.Meds.RemoveAll(med => !med.IsSelected));
As being reference type, despite you create new list using ToList() method, it will point to same location. So, the result also will be reflected at patientsMeds variable
just use:
var bb = patientMedsList.Where(p => p.Patient.IsSelected).ToList().Select(p => new PatientMeds { Patient = p.Patient, Meds = p.Meds.Where(m => m.IsSelected).ToList() }).ToList();
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
This is my code that works great:
IPRepository rep = new IPRepository();
var Q = rep.GetIp()
.Where(x => x.CITY == CITY)
.GroupBy(y => o.Fam)
.Select(z => new IpDTO
{
IId = z.Key.Id,
IP = z.Select(x => x.IP).Distinct()
});
IP is IEnumerable<string>
I need to add to this code above a call to a function PAINTIP(ip).
I need to send each one of the elements that will be inside IP to a function PAINTIP(ip).
therefore i need to use some kind of foreach function but i cannot figure out how.
rep.GetIp()
.Where(x => x.CITY == CITY)
.GroupBy(y => o.Fam)
.Select(z => new IpDTO
{
IId = z.Key.Id,
IP = z.Select(x => x.IP).Distinct()
})
.SelectMany(item => item.IP)
.ToList()
.ForEach(PAINTIP)
You can do something like this :
var result = from item in collection
.Where(i => i.condition == value)
.Select(i => new{ Name = i.name, Description = i.Description })
.ToList().ForEach(i => Function(i));
Hope this help !
Very similiar to the answer of this question
LINQ equivalent of foreach for IEnumerable<T>
There is no For Each for an IEnumerable but there is for List
items.ToList().ForEach(i => i.DoStuff());
Edit
I'm not sure you can do it in the way you want to other than this:
ep.GetIp()
.Where(x => x.CITY == CITY)
.GroupBy(y => o.Fam)
.Select(z => new IpDTO
{
IId = z.Key.Id,
IP = z.Select(x => x.IP).Distinct()
})
.ToList().ForEach(IpObj => IpObj.IP.ToList().ForEach(ip => PAINTIP(ip));
This way you get your list of IpDTO objects out first. Then Enumerate over each and then in turn over each IpDTO objects IP IEnumerable. I haven't seen a way to do it where you can Enumerate inside the creation of your IpDTO object. If someone has an example of how to do so I'd like to see to learn myself.
I am trying something that i not really sure but i want to ask here if it s possible.
Is it able to be done ?
public IQueryable<Info> GetInfo(int count, byte languageId)
{
return db.Info.SelectMany(i => i.LanguageInfo)
.Where(l => l.Language.id == languageId)
.Select(l => new Info { AddDate = l.Info.AddDate,
Description = l.Description,
EntityKey = l.Info.EntityKey,
id = l.Info.id,
Title = l.Title,
ViewCount = l.Info.ViewCount }
)
.OrderByDescending(i => i.id)
.Take(count);
}
When this method is executed i got an error
The entity or complex type
'GuideModel.Info' cannot be
constructed in a LINQ to Entities
query.
Does it mean "not possible" ?
Thank you
The error essentially indicates that the Entity Framework doesn't know how to create an Info object, since it is not bound to a table object. (Put another way, the Select call on the IQueryable cannot be translated into equivalent SQL.) You could perform the Select projection on the client via:
public IQueryable<Info> GetInfo(int count, byte languageId)
{
return db.Info.SelectMany(i => i.LanguageInfo)
.Where(l => l.Language.id == languageId)
.Take(count)
.AsEnumerable()
.Select(l => new Info { AddDate = l.Info.AddDate,
Description = l.Description,
EntityKey = l.Info.EntityKey,
id = l.Info.id,
Title = l.Title,
ViewCount = l.Info.ViewCount }
)
.OrderByDescending(i => i.id);
}
It is possible to use Select(l => new ...), but not with an Entity type. You need to use an anonymous type or a POCO type with a parameterless constructor. Entity types are "special" because of the way they interact with the ObjectContext. You can select them, but not new them up in a query.
The code below worked for me. Here "SearchTerm" is a complex type. Thanks Jason :)
var lstSynonym = TechContext.TermSynonyms
.Where(p => p.Name.StartsWith(startLetter))
.AsEnumerable()
.Select(u => new SearchTerm
{
ContentId = u.ContentId,
Title = u.Name,
Url = u.Url
});