I have a simple linq lambda statement
Interactions = new BindableCollection<InteractionDTO>(ctx.Interactions.Where(x => x.ActivityDate > DateTime.Today)
.Select(x => new InteractionDTO
{
Id = x.Id,
ActivityDate = x.ActivityDate,
subject = x.Subject,
ClientNames = x.Attendees.Count == 1 ? x.Attendees.FirstOrDefault().Person.CorrespondenceName :
x.Attendees.FirstOrDefault().Person.CorrespondenceName : "Multiple attendees"
}));
This will give me the first Client Name, I'm trying to have it appear First 2 attendees followed by dots. I tried this
ClientNames = x.Attendees.Count == 1 ?
x.Attendees.FirstOrDefault().Person.CorrespondenceName :
x.Attendees.FirstOrDefault().Person.CorrespondenceName +
x.Attendees.Skip(1).FirstOrDefault().Person.CorrespondenceName + " ..."
But I get this error:
The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.
You could try ordering first, as the message suggests.
I'm not sure what your Attendees class looks like, but assuming it has an ID field:
x.Attendees.OrderBy(a => a.ID)
.Skip(1)
.Select(a => a.Person.CorrespondenceName).FirstOrDefault() + " ..."
A couple other notes:
I swapped your Select and FirstOrDefault statements. The way you've currently got it, if FirstOrDefault() returns null, then Person.CorrespondenceName will throw an exception.
But now if no record is found, you'll end up with just "...". You might want to adjust your first Where clause to filter out records that have no correspondance name, and then change FirstOrDefault() to First().
EDIT:
That should steer you in the right direction (I hope). This may be more what you're looking for, assuming it can actually be translated into a valid SQL statement:
ClientNames = x.Attendees.Any()
? x.Attendees.Count == 1
? x.Attendees.Select(a => a.Person.CorrespondenceName).FirstOrDefault()
: x.Attendees.Count == 2
? string.Join(", ", x.Attendees.OrderBy(a => a.ID).Take(2)
.Select(a => a.Person.CorrespondenceName).FirstOrDefault()
: string.Join(", ", x.Attendees.OrderBy(a => a.ID).Take(2)
.Select(a => a.Person.CorrespondenceName).FirstOrDefault() + " ..."
: "No client name available";
// put this in your namespace...
public static class EnumerableExtension
{
public static TSource SecondOrDefault<TSource>(this IEnumerable<TSource> source)
{
var iterator = source.GetEnumerator();
if (iterator.MoveNext() && iterator.MoveNext() )
return iterator.Current;
else
return default( TSource );
}
}
// Usage... var thing = list.SecondOrDefault();
Related
I have the following table in sql
I am trying to select all records with a status of onboard, but however you can see thatfor user '43d658bc-15a7-4056-809a-5c0aad6a1d86' i have two onboard entries. How do i select the firstordefault entry if the user has more than one record?
so my expected outcome should be
this is what i have that gets all the records
public async Task<List<Model>> HandleAsync(Query query)
{
return (await _repository.GetProjectedListAsync(q=> q.Where(x => x.Status== "Onboard").Select( Project.Log_Model))).ToList();
}
internal static partial class Project
{
public static readonly Expression<Func<Log,Model>> Log_Model =
x => x == null ? null : new Model
{
Id = x.Id,
UserId = x.UserId,
Status = x.Status,
created=x.Created,
DepartmentId=x.DepartmentId
};
}
i tried the following
var test = (await _repository.GetProjectedListAsync(q=> q.Where(x => x.Status== "Onboard").Select( Project.Log_Model))).ToList();
var t= test.FirstOrDefault();
return t;
but i get an error "can not implicitly convert type model to system.collections.generic.list"
The following code example demonstrates how to use FirstOrDefault() by passing in a predicate. In the second call to the method, there is no element in the array that satisfies the condition. You can filter out an entry you are looking for directly in the FirstOrDefault().
If you don't want to have duplicates, you could also use Distinct.
string[] names = { "Hartono, Tommy", "Adams, Terry",
"Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };
string firstLongName = names.FirstOrDefault(name => name.Length > 20);
Console.WriteLine("The first long name is '{0}'.", firstLongName);
string firstVeryLongName = names.FirstOrDefault(name => name.Length > 30);
Console.WriteLine(
"There is {0} name longer than 30 characters.",
string.IsNullOrEmpty(firstVeryLongName) ? "not a" : "a");
/*
This code produces the following output:
The first long name is 'Andersen, Henriette Thaulow'.
There is not a name longer than 30 characters.
*/
I am just trying to concatenate a string on to a column returned from the database like so:
var aaData =
(from pr in ctx.PaymentRates
where pr.ServiceRateCodeId == new Guid("BBCE42CB-56E3-4848-B396-4656CCE3CE96")
select new
{
Id = pr.Id,
Rate = pr.YearOneRate + "helloWorld"
})
.ToList();
It gives me this error:
Unable to cast the type 'System.Nullable`1' to type 'System.Object'.
LINQ to Entities only supports casting EDM primitive or enumeration
types.
So, then I tried this:
var aaData =
(from pr in ctx.PaymentRates
where pr.ServiceRateCodeId == new Guid("BBCE42CB-56E3-4848-B396-4656CCE3CE96")
select new
{
pr = pr
})
.AsEnumerable()
.Select(x => new
{
Id = x.pr.Id,
Rate = x.pr.YearOneRate + "helloWorld"
})
.ToList();
But, now it gives me this error:
Object reference not set to an instance of an object.
On this line:
.Select(x => new
How can I concatenate these strings in LINQ?
The quick solution
Regarding your second code chunk I need to point out to you that you're actually doing two left outer joins on the Countries table/set, one for homeC and one for hostC.
That means that you are willing to accept null values for those two variables.
In other words, since they can be null you are somehow allowing this right here to crash with NullReferenceException, should those variables turn out to be null:
.Select(x => new
{
Id = x.pr.Id,
HomeCountry = x.homeC.Name,
HostCountry = x.hostC.Name,
Rate = x.pr.YearOneRate + "helloWorld"
})
The error (NullReferenceException or as you saw it's message: "Object reference not set to an instance of an object.") is not here
.Select(x =>
but rather here
x.homeC.Name and x.hostC.Name
where you will most certainly dereference a null reference.
That's just Visual Studio's way of pointing out the best statement that fits around the error.
So, the quickest solution would be to do this:
.Select(x => new
{
Id = x.pr.Id,
HomeCountry = (x.homeC != null) ? x.homeC.Name : "HomeCountry not found",
HostCountry = (x.hostC.Name != null) ? x.hostC.Name : "HostCountry not found",
Rate = x.pr.YearOneRate + "helloWorld"
})
Notice the modification which ensures that you will still be able to extract some information from result set records for which homeC and hostC are null.
EDIT
Regarding the first query you posted:
var aaData =
(from pr in ctx.PaymentRates
where pr.ServiceRateCodeId == new Guid("BBCE42CB-56E3-4848-B396-4656CCE3CE96")
select new
{
Id = pr.Id,
Rate = pr.YearOneRate + "helloWorld"
})
.ToList();
my guess is that your 'YearOnRate' property is of type 'Nullable< of something >" (maybe decimal -- so for instance it is maybe a decimal? YearOnRate { get; set; }) and the corresponding column in the database is a nullable one.
If that is the case, then I think (in this first version of your endeavour) you could try to do this:
Rate = (pr.YearOnRate != null) ? pr.YearOneRate.Value + "helloWorld" : "[null]helloWorld"
and get away with it.
My guess is that either x.homeC, x.hostC, or x.pr are null. If you're fine using AsEnumerable to convert to Linq-to-Objects then you could just change your projection to
.Select(x => new
{
Id = (x.pr.HasValue ? x.pr.Id : 0),
HomeCountry = (x.homeC.HasValue ? x.homeC.Name : null),
HostCountry = (x.hostC.HasValue ? x.hostC.Name : null),
Rate = (x.pr.HasValue ? x.pr.YearOneRate : null) + "helloWorld"
})
My problem was, I wasn't using .AsEnumerable() properly. The code below works:
var aaData =
(from pr in ctx.PaymentRates
from homeC in ctx.Countries.Where(x => x.Id == pr.HomeCountryId).DefaultIfEmpty()
from hostC in ctx.Countries.Where(x => x.Id == pr.HostCountryId).DefaultIfEmpty()
from curr in ctx.Currencies.Where(x => x.Id == pr.YearOneCurrencyId).DefaultIfEmpty()
where pr.ServiceRateCodeId.Value.Equals(new Guid("BBCE42CB-56E3-4848-B396-4656CCE3CE96"))
select new { pr, homeC, hostC, curr })
.AsEnumerable()
.Select(x => new
{
Id = (string)(x.pr.Id.ToString() + "test"),
HomeCountry = (x.homeC != null ? x.homeC.Name : ""),
HostCountry = (x.hostC != null ? x.hostC.Name : ""),
Rate = (x.pr.YearOneRate ?? 0) + " (" + x.curr.Code + ")"
})
.ToList();
You have used DefaultIfEmpty on both homeC and hostC so you can get a null reference when you call homeC.Name or hostC.Name
Try using HomeCountry = homeC == null ? null : homeC.Name instead
If pr.YearOneRate is not a string and you want the concatenation done by the database engine you need to tell Linq-to-Entities to generate sql to convert it. If you are using Sql Server you can use this:
SqlFunctions.StringConvert(pr.YearOneRate) + "helloWorld"
If you don't need the concatenation done in the database then you can use AsEnumerable() before the Select so that you are running Linq-To-Objects
I am trying to make a suitable linq query to accomodate my search functionality.
I have a table with the following columns: 'firstname' | 'lastname' | 'description'.
with the following data: 'Peter' | 'Mulder' | 'This is a little description.'
My 'search' keyword could be something like: "peter" or "a little description".
Now if I use the following linq expression in lambda:
mycontext.persons
.Where(t =>
search.Contains(t.Firstname) ||
search.Contains(t.Lastname) ||
search.Contains(t.Description).Select(p => p)
.ToList();
Now I get my result, when I use 'peter', but if I use 'pete' or 'a little description' I get no results.
How can I make my linq expression, so it can search through the column data for matches?
I think you just have it backwards:
mycontext.persons
.Where(t =>
t.Firstname.Contains(search) ||
t.Lastname.Contains(search) ||
t.Description.Contains(search))
.ToList();
One possible (but probably not the most optimized solution) would be to append all of your fields together and do a Contains on the search term., e.g.
var result = persons.Where(q => (q.Description + " " q.FirstName + " " q.LastName)
.ToLower()
.Contains(searchTerm.ToLower()))
.ToList();
try This Code.
private void SearchData()
{
Model1Container model = new Model1Container();
try
{
var query = model.Scholars.AsQueryable();
if (!string.IsNullOrEmpty(this.txtSearch.Text))
{
// query = query.Where(x=>x.ScholarName.StartsWith(txtSearch.Text));
query = (from Schl in model.Scholars
where Schl.ScholarName.StartsWith(txtSearch.Text) ||
Schl.PhoneRes.StartsWith(txtSearch.Text) ||
Schl.PhoneOff.StartsWith(txtSearch.Text) ||
Schl.Mobile.StartsWith(txtSearch.Text) ||
Schl.Email.StartsWith(txtSearch.Text)
orderby Schl.ScholarName
select Schl);
}
this.dgvScholarList.DataSource = query.ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a problem trying to implement a filtering expression to filter a list of entities :
The LINQ expression node type 'Invoke' is not supported in LINQ to
Entities.
This is the code :
public IList<DocumentEntry> GetDocumentEntriesForRateAdjustmentTry2(
string username, Rate rate, List<RatePeriod> ratePeriods)
{
var dimensionLibManager = new DimensionLibManager();
var currentVersionRateGroups = rate.CurrentRateVersion.RateGroups.ToList();
Expression<Func<DocumentEntry, IList<RateGroup>, int, bool>> dimensionMatchesExpression =
(documentEntry, rateGroups, dimensionInfoId) =>
rateGroups.Any(
rg =>
rg.Dimension1.All(character => character == '*')
||
documentEntry.DocumentEntryDimensions.Any(
ded =>
ded.DimensionInfo.Position == dimensionInfoId
&&
dimensionLibManager.GetDimensionSegments(rate.CompanyId, username, dimensionInfoId, ded.Value).Any(
seg => ded.Value.Substring(seg.SegmentStart, seg.SegmentLength) == seg.SegmentValue)));
var dimensionMatches = dimensionMatchesExpression.Compile();
var documentEntries = this.ObjectSet.Where(de => dimensionMatches(de, currentVersionRateGroups, 1));
var result = documentEntries.ToList(); // The error happens here.
return result;
}
I suspect that dimensionMatchesExpression cannot be traduced into SQL because inside it calls another library's method (dimensionLibManager.GetDimensionSegments) to filter documents based on specific parameters.
Is there a way (other than using LinqKit or any additionnal extention library) that I can make this work ?
The reason why I want to use an Expression to act as a filter is because, ultimately, I would like to to this :
var documentEntries = this.ObjectSet.Where(de =>
dimensionMatches(de, currentVersionRateGroups, 1)
&& dimensionMatches(de, currentVersionRateGroups, 2)
&& dimensionMatches(de, currentVersionRateGroups, 3)
&& dimensionMatches(de, currentVersionRateGroups, 4));
Also, how can I actually debug that kind of problem ? The error message is pretty vague. How can I track down the exact node that is causing the error ?
I suspect this is the issue.
var documentEntries = this.ObjectSet.Where(de => dimensionMatches(de, currentVersionRateGroups, 1));
I don't think that row number works with Linq2EF.
public IList<DocumentEntry> GetDocumentEntriesForRateAdjustmentTry2(
string username, Rate rate, List<RatePeriod> ratePeriods)
{
var dimensionLibManager = new DimensionLibManager();
var currentVersionRateGroups = rate.CurrentRateVersion.RateGroups.ToList();
Expression<Func<DocumentEntry, int, bool>> dimensionMatchesExpression =
(documentEntry, rateGroups, dimensionInfoId) =>
currentVersionRateGroups.Any(
rg =>
rg.Dimension1.All(character => character == '*')
||
documentEntry.DocumentEntryDimensions.Any(
ded =>
ded.DimensionInfo.Position == dimensionInfoId
&&
dimensionLibManager.GetDimensionSegments(rate.CompanyId, username, dimensionInfoId, ded.Value).Any(
seg => ded.Value.Substring(seg.SegmentStart, seg.SegmentLength) == seg.SegmentValue)));
var documentEntries = this.ObjectSet.Where(dimensionMatchesExpression);
var result = documentEntries.ToList(); // The error happens here.
return result;
}
Although I don't understand why you want to use an expression to do this. You could just inline it all...
Just realised a few days ago the solution to your problem...bit of a hack...
public Expression<Func<DocumentEntry, int, bool>> CreateWhereClause(stuff);
public IList<DocumentEntry> GetDocumentEntriesForRateAdjustmentTry2(
string username, Rate rate, List<RatePeriod> ratePeriods)
{
using(var db = new Context())
{
IQueryable<DocumentEntry> foo = db.Foos;
foreach(var i =0; i <4; i++)
{
foo = foo.Where(DocumentEntry(i));
}
}
}
We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?
if you want to only filter if certain criteria is passed, do something like this
var logs = from log in context.Logs
select log;
if (filterBySeverity)
logs = logs.Where(p => p.Severity == severity);
if (filterByUser)
logs = logs.Where(p => p.User == user);
Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less.
If you need to filter base on a List / Array use the following:
public List<Data> GetData(List<string> Numbers, List<string> Letters)
{
if (Numbers == null)
Numbers = new List<string>();
if (Letters == null)
Letters = new List<string>();
var q = from d in database.table
where (Numbers.Count == 0 || Numbers.Contains(d.Number))
where (Letters.Count == 0 || Letters.Contains(d.Letter))
select new Data
{
Number = d.Number,
Letter = d.Letter,
};
return q.ToList();
}
I ended using an answer similar to Daren's, but with an IQueryable interface:
IQueryable<Log> matches = m_Locator.Logs;
// Users filter
if (usersFilter)
matches = matches.Where(l => l.UserName == comboBoxUsers.Text);
// Severity filter
if (severityFilter)
matches = matches.Where(l => l.Severity == comboBoxSeverity.Text);
Logs = (from log in matches
orderby log.EventTime descending
select log).ToList();
That builds up the query before hitting the database. The command won't run until .ToList() at the end.
I solved this with an extension method to allow LINQ to be conditionally enabled in the middle of a fluent expression. This removes the need to break up the expression with if statements.
.If() extension method:
public static IQueryable<TSource> If<TSource>(
this IQueryable<TSource> source,
bool condition,
Func<IQueryable<TSource>, IQueryable<TSource>> branch)
{
return condition ? branch(source) : source;
}
This allows you to do this:
return context.Logs
.If(filterBySeverity, q => q.Where(p => p.Severity == severity))
.If(filterByUser, q => q.Where(p => p.User == user))
.ToList();
Here's also an IEnumerable<T> version which will handle most other LINQ expressions:
public static IEnumerable<TSource> If<TSource>(
this IEnumerable<TSource> source,
bool condition,
Func<IEnumerable<TSource>, IEnumerable<TSource>> branch)
{
return condition ? branch(source) : source;
}
When it comes to conditional linq, I am very fond of the filters and pipes pattern.
http://blog.wekeroad.com/mvc-storefront/mvcstore-part-3/
Basically you create an extension method for each filter case that takes in the IQueryable and a parameter.
public static IQueryable<Type> HasID(this IQueryable<Type> query, long? id)
{
return id.HasValue ? query.Where(o => i.ID.Equals(id.Value)) : query;
}
Doing this:
bool lastNameSearch = true/false; // depending if they want to search by last name,
having this in the where statement:
where (lastNameSearch && name.LastNameSearch == "smith")
means that when the final query is created, if lastNameSearch is false the query will completely omit any SQL for the last name search.
Another option would be to use something like the PredicateBuilder discussed here.
It allows you to write code like the following:
var newKids = Product.ContainsInDescription ("BlackBerry", "iPhone");
var classics = Product.ContainsInDescription ("Nokia", "Ericsson")
.And (Product.IsSelling());
var query = from p in Data.Products.Where (newKids.Or (classics))
select p;
Note that I've only got this to work with Linq 2 SQL. EntityFramework does not implement Expression.Invoke, which is required for this method to work. I have a question regarding this issue here.
It isn't the prettiest thing but you can use a lambda expression and pass your conditions optionally. In TSQL I do a lot of the following to make parameters optional:
WHERE Field = #FieldVar OR #FieldVar IS NULL
You could duplicate the same style with a the following lambda (an example of checking authentication):
MyDataContext db = new MyDataContext();
void RunQuery(string param1, string param2, int? param3){
Func checkUser = user =>
((param1.Length > 0)? user.Param1 == param1 : 1 == 1) &&
((param2.Length > 0)? user.Param2 == param2 : 1 == 1) &&
((param3 != null)? user.Param3 == param3 : 1 == 1);
User foundUser = db.Users.SingleOrDefault(checkUser);
}
I had a similar requirement recently and eventually found this in he MSDN.
CSharp Samples for Visual Studio 2008
The classes included in the DynamicQuery sample of the download allow you to create dynamic queries at runtime in the following format:
var query =
db.Customers.
Where("City = #0 and Orders.Count >= #1", "London", 10).
OrderBy("CompanyName").
Select("new(CompanyName as Name, Phone)");
Using this you can build a query string dynamically at runtime and pass it into the Where() method:
string dynamicQueryString = "City = \"London\" and Order.Count >= 10";
var q = from c in db.Customers.Where(queryString, null)
orderby c.CompanyName
select c;
You can create and use this extension method
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool isToExecute, Expression<Func<TSource, bool>> predicate)
{
return isToExecute ? source.Where(predicate) : source;
}
Just use C#'s && operator:
var items = dc.Users.Where(l => l.Date == DateTime.Today && l.Severity == "Critical")
Edit: Ah, need to read more carefully. You wanted to know how to conditionally add additional clauses. In that case, I have no idea. :) What I'd probably do is just prepare several queries, and execute the right one, depending on what I ended up needing.
You could use an external method:
var results =
from rec in GetSomeRecs()
where ConditionalCheck(rec)
select rec;
...
bool ConditionalCheck( typeofRec input ) {
...
}
This would work, but can't be broken down into expression trees, which means Linq to SQL would run the check code against every record.
Alternatively:
var results =
from rec in GetSomeRecs()
where
(!filterBySeverity || rec.Severity == severity) &&
(!filterByUser|| rec.User == user)
select rec;
That might work in expression trees, meaning Linq to SQL would be optimised.
Well, what I thought was you could put the filter conditions into a generic list of Predicates:
var list = new List<string> { "me", "you", "meyou", "mow" };
var predicates = new List<Predicate<string>>();
predicates.Add(i => i.Contains("me"));
predicates.Add(i => i.EndsWith("w"));
var results = new List<string>();
foreach (var p in predicates)
results.AddRange(from i in list where p.Invoke(i) select i);
That results in a list containing "me", "meyou", and "mow".
You could optimize that by doing the foreach with the predicates in a totally different function that ORs all the predicates.