I'm using linq in nhibernate and I have problem when I try to use OrderBy using Dynamic Linq:
var bugAndFeatures = (from u in session.Query<BugAndFeature>()
let uEmployeeFullName = string.Format("{0} {1}", u.Employee.Surname, u.Employee.FirstName)
where u.IsDelete == false
select new BugAndFeatureView()
{
Id = u.Id,
Title = u.Title,
Description = u.Description,
EmployeeFullName = uEmployeeFullName,
EmployeeLogin = u.Employee.User.Login,
AssignedEmployeeId = u.AssignedEmployee == null ? 0 : u.AssignedEmployee.Id,
AssignedEmployeeFullName = string.Format("{0} {1}", u.AssignedEmployee.Surname, u.AssignedEmployee.FirstName),
CreateDate = u.CreateDate.Equals(null) ? string.Empty : u.CreateDate.ToString(),
LastUpdateDate = u.LastUpdateDate.Equals(null) ? string.Empty : u.LastUpdateDate.ToString()
}
);
After that I would like to use dynamic linq and use OrderBy like OrderBy("EmployeeFullName DESC") and I couldn't do that because I have exception.
I noticed that when I'm doing OrderBy on any property which I don't format or check null etc. I don't have this problem it only occurs when I try to do orderby with formated properties.
If I do ToList() before OrderBy then I don't have this problem but I don't want to do that I need use IQueryable.
How can I modify this query to solve my issue?
Thanks for help.
Have you try like this:
var Results = bugAndFeatures.ToList().OrderBy(p => p.EmployeeFullName);
IQueryable<Foo> query = ...;
switch (orderByParameter)
{
case "SomeValueParamter":
query = query.OrderBy(x => x.SomeValueParamter);
break;
case "SomeValueParamter":
query = query.OrderBy(x => x.SomeValueParamter);
break;
// etc
}
Related
I'm trying to create a linq query where clause is a constructed variable based on user choices
if (!string.IsNullOrEmpty(txbbox.Text))
{
query = "s.date== DateTime.Parse(txbbox.Text)";
}
if (!string.IsNullOrEmpty(txbbox.Text))
{
query = query + " & (s.type.Contains(txbbox.Text))";
}
there is a way to pass the variable built in the where clause in a LINQ query?
Stemp = (from s in SList
where ***query***
orderby s.DataScadenza
select s).ToList();
Yes; quite simple in this case, actually:
IEnumerable<Whatever> query = SList; // avoid var here, as will impact later assignment
if (!string.IsNullOrEmpty(txbbox.Text))
{
var when = DateTime.Parse(txbbox.Text); // to avoid parsing per item
query = query.Where(s => s.date == when);
}
if (!string.IsNullOrEmpty(txbbox.Text))
{
query = query.Where(s => s.type.Contains(txbbox.Text));
}
Stemp = query.OrderBy(s => s.DateScadenze).ToList();
I have some linq code that I am trying to refactor because its not very good:
Basically, I am wondering if there is a better way to perform the following:
if (!string.IsNullOrWhiteSpace(_filter.AssignedTo)
{
var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
&& cUser.GetUserNameUsingGUID(ticket.AssignTicketToUser) == _filter.AssignedTo
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};
}
else
{
var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};
}
They are both identical apart from the where clause is checks for AssignTicketToUser.
I am hoping there is a nicer way to do this to avoid having to use an if else statement? I have a few of these code blocks and dont want to be duplicating code alot!
var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
&& (string.IsNullOrWhiteSpace(_filter.AssignedTo) ? true : cUser.GetUserNameUsingGUID(ticket.AssignTicketToUser) == _filter.AssignedTo)
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};
You can get rid of the if-else statement altogether. Transfer the if condition it to the 2nd where clause, and remove the !. That second where clause becomes a ternary operator.
If the condition is true, that is if _filter.AssignedTo is null, then don't test _filter.AssignedTo by returning true. If it's not null or empty, then proceed to the clause that was there in your original else block.
one way could be:
var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};
if (!string.IsNullOrWhiteSpace(_filter.AssignedTo)
query = query.Where(w => cUser.GetUserNameUsingGUID(w.AssignTicketToUser) == _filter.AssignedTo));
Take a look at the PredicateBuilder implementation from C# In a Nutshell, the And method should address your issue here, in a more generic way, and help build an understanding of LINQ and expression trees. You would end up with something like:
var query = from ticket in dataClassesDataContext.TicketsIssues
where ticket.ClosedDate == null
select new
{
Priority = ticket.TicketPriority.TicketPriorityName,
Description = ticket.Description.Replace("\n", ", "),
};
if (!string.IsNullOrWhiteSpace(_filter.AssignedTo))
{
query = query.And(ticket => cUser.GetUserNameUsingGUID(ticket.AssignTicketToUser) == _filter.AssignedTo);
}
I have List List courseTakenList.i want to filter out the Status which are in Completed,Dropped,Current,Schudeled. Here is the code sample.
courseTakenList = (from courseTaken in courseTakenList
select new Course
{
Status = "Scheduled"?"COMPLETE"?"Dropped"? "Current"
}).ToList();
You could do it even more concise
var statuslist= {"Completed","Dropped","Current","Schudeled"};
var courses = courseTakenList.Where(courseTaken =>
statuslist.Contains(courseTaken.Status);
Linq In query like this will resolve your issue
var statuslist= {"Completed","Dropped","Current","Schudeled"};
var query = from courseTaken in courseTakenList
where statuslist.Contains( courseTaken .Status )
select courseTaken ;
Note : change select clause as you want
I have the following code. The function has a lot of Linq calls and I had help on putting this into place.
public IList<Content.Grid> Details(string pk)
{
IEnumerable<Content.Grid> details = null;
IList<Content.Grid> detailsList = null;
var data = _contentRepository.GetPk(pk);
var refType = this.GetRefType(pk);
var refStat = this.GetRefStat(pk);
var type = _referenceRepository.GetPk(refType);
var stat = _referenceRepository.GetPk(refStat);
details =
from d in data
join s in stat on d.Status equals s.RowKey into statuses
from s in statuses.DefaultIfEmpty()
join t in type on d.Type equals t.RowKey into types
from t in types.DefaultIfEmpty()
select new Content.Grid
{
PartitionKey = d.PartitionKey,
RowKey = d.RowKey,
Order = d.Order,
Title = d.Title,
Status = s == null ? null : s.Value,
StatusKey = d.Status,
Type = t == null ? null : t.Value,
TypeKey = d.Type,
Link = d.Link,
Notes = d.Notes,
TextLength = d.TextLength
};
detailsList = details
.OrderBy(item => item.Order)
.ThenBy(item => item.Title)
.Select((t, index) => new Content.Grid()
{
PartitionKey = t.PartitionKey,
RowKey = t.RowKey,
Row = index + 1,
Order = t.Order,
Title = t.Title,
Status = t.Status,
StatusKey = t.StatusKey,
Type = t.Type,
TypeKey = t.TypeKey,
Link = t.Link,
Notes = t.Notes,
TextLength = t.TextLength,
})
.ToList();
return detailsList;
}
The first uses one format for Linq and the second another. Is there some way that I could simplify and/or combine these? I would really like to make this code simpler but I am not sure how to do this. Any suggestions would be much appreciated.
Of course you can combine them. The Linq keywords such as from, where and select get translated into calls like the Extension methods that you call below, so effectively there's no difference.
If you really want to combine them, the quickest way is to put () around the first query, then append the method calls you use on details in the second query. Like this:
detailsList =
(from d in data // <-- The first query
// ...
select new Content.Grid
{
// ...
})
.OrderBy(item => item.Order) // <-- The calls from the second query
.ThenBy(item => item.Title)
.Select((t, index) => new Content.Grid()
{
//...
}).ToList();
But i think that would be ugly. Two queries are just fine IMO.
List<HelprClass.Organizer> org =
( from EventOrg in cntx.EventOrganizer
from MstrOrg in cntx.Organizer
where EventOrg.OrganizerID == MstrOrg.OrganizerID
Select new HelprClass.Organizer
{
OrganizerName = MstrOrg.OrganizerName
}).ToList()
This work fine now i want to use IN Opeartor in the above Query.
in the EventOrganizer I have EventID now i want to select only Event ID exsist in EventOrganizer collection
I have EventID another var varibale
Var EventID= From EvntID in Evetn Select new {ID= EvntID.EventID};
Something like this
where
EventOrg.OrganizerID == MstrOrg.OrganizerID
&& EventOrg.EventID in EventID.ID
How I can achive this ?
I will appreciate your help
Try this:
var EventIDs = from EvntID in Event select EvntID.EventID;
var org = (from EventOrg in cntx.EventOrganizer
from MstrOrg in cntx.Organizer
where EventOrg.OrganizerID == MstrOrg.OrganizerID
select new {E=EventOrg, M=MstrOrg}
).ToList();
org = org
.Where(o => EventIDs.Contains(o.E.EventID) )
.Select(o => new HelprClass.Organizer
{
OrganizerName = o.M.OrganizerName
}
);
If you are using Entity Framework you can not use a Contains statement, which would be an easy solution in Linq. SO if it's just Linq 2 Entities, use a where clause like "where EventId.Contains(EventOrg.Id)"
If you are indeed using Entity Framework you will have to build an or expression based on the Id's in the EventID Collection.