I have a search result from the database,
int searchTerm = "xx"
var result = from orderLines in context.OrderLineSearch(searchTerm)
select new
{
OrderNumber = orders.OrderNumber,
OrderLineId = orders.OrderLineId
};
I need to validate whether result contains many orders. That is I need to check whether multiple orders are returned or not.
I did the validation by storing the first order number in a variable and compared whether all the other rows contains only this order number. See below
string orderNumber = result.First().OrderNumber;
bool isValid = result.Where(x => x.OrderNumber != orderNumber).Count() == 0;
I want to know the best way to validate using LINQ? Can any one help me?
Thanks in advance.
May be you should to try group results by OrderNumber and then calculate Count?
var result = from orderLines in context.OrderLineSearch(searchTerm)
group orderLines by orderLines.OrderNumber into g
select g.Key
bool hasElements = result.Any();
Related
This is more a question in regard to best performance way to handle this. I have two lists that have a invoice number and balance. I need to get the value from my first list that the invoice number equals the invoice number from the 2nd list and the balance is different. Is Linq except the best way to handle this delta or is there a better way. Example lists:
var collection1 = new List<InvoiceBalances>();
var collection2 = new List<InvoiceReconcile>();
Looking for all value in the 1st collection1 InvoiceNumber = InvoiceNumber and Balance not equal.
Using LINQ you can do this :
var res = collection1.Where(x => collection2.Any(y => y.InvoiceNumber == x.InvoiceNumber && y.Balance != x.Balance));
This query will fetch all the entries in collection1 which has corresponding entry in collection2 such that their InvoiceNumber is same but Balance is different.
var query = db.Customers
.Where("City == #0 and Orders.Count >= #1", "London", 10)
.OrderBy(someStringVariable)
.Select("new(CompanyName as Name, Phone)");
How can I check if someStringVariable is a valid order by expression before I run this query?
I want to check it instead of catching ParseException.
Valid string: "City ASC, Phone DESC"
Invalid string is not existing field or mistype in DESC: "City1 DESC1"
With help of Anu I am using this function but I would prefer some "TryParseQuery" in the Linq.Dynamic namespace.
public static bool IsValidOrderString(Type type, string ordering)
{
if (string.IsNullOrWhiteSpace(ordering)) return false;
var orderList = ordering.Trim().Split(',');
var fields = type.GetProperties().Select(property => property.Name).ToArray();
foreach (var orderItem in orderList)
{
var order = orderItem.TrimEnd();
if (order.EndsWith(" ASC", StringComparison.InvariantCultureIgnoreCase) || order.EndsWith(" DESC", StringComparison.InvariantCultureIgnoreCase)) order = order.Substring(0, order.Length - 4);
if (!fields.Contains(order.Trim())) return false;
}
return true;
}
as #mjwills pointed out, it is hard to do it with 100% reliability, but one thing you could do is compare 'someStringVariable' with list of columns in your table. You can find the list of columns via
.GetProperties().Select(property => property.Name).ToArray();
Again you need to be aware that this has many pitfalls. Properties can be mapped to column names that are not same as the property name.
I have 2 list of items;
IEnumerable<Investigator> investigators = RepositoryContext.InvestigatorRep.GetInvestigators(site.Site.Id, out totalCount);
var NewInvestigators = base.ActivePage.Investigators;
I have 30 items in investigators and 20 items in NewInvesigators, both have property Id, InvId I need to match that.
var all = investigators.Where(b => crInvestigators.Any(a => a.InvestigatorId == b.Id));
I tried this but not worked
I want to create a new list based on matching Id of those two lists. If Id matches get the particular investigator(basically a sort on investigators based on Id existing in NewInvesigators).
I can do it by using for each, but I want to know whether it is possible with linq?
in newinvestigator I have object which is having two property, investigatorId and Name.
In Investigator I have property Id , City , country.
no Name or investigatorId in the investigator list.
You could try something like this:
var result = investigators.Where(inv=>NewInvestigators.Any(ninv=>ninv.id == inv.investigatorId))
.OrderBy(inv=>inv.id);
Another way to get the same result is using a join.
var result = from inv in investigators
join ninv in NewInvestigators
on inv.id equals ninv.investigatorId
order by inv.id
select inv;
I retrieve data from two different repositories:
List<F> allFs = fRepository.GetFs().ToList();
List<E> allEs = eRepository.GetEs().ToList();
Now I need to join them so I do the following:
var EFs = from c in allFs.AsQueryable()
join e in allEs on c.SerialNumber equals e.FSerialNumber
where e.Year == Convert.ToInt32(billingYear) &&
e.Month == Convert.ToInt32(billingMonth)
select new EReport
{
FSerialNumber = c.SerialNumber,
FName = c.Name,
IntCustID = Convert.ToInt32(e.IntCustID),
TotalECases = 0,
TotalPrice = "$0"
};
How can I make this LINQ query better so it will run faster? I would appreciate any suggestions.
Thanks
Unless you're able to create one repository that contains both pieces of data, which would be a far preferred solution, I can see the following things which might speed up the process.
Since you'r always filtering all E's by Month and Year, you should do that before calling ToList on the IQueryable, that way you reduce the number of E's in the join (probably considerably)
Since you're only using a subset of fields from E and F, you can use an anonymous type to limit the amount of data to transfer
Depending on how many serialnumbers you're retrieving from F's, you could filter your E's by serials in the database (or vice versa). But if most of the serialnumbers are to be expected in both sets, that doesn't really help you much further
Reasons why you might not be able to combine the repositories into one are probably because the data is coming from two separate databases.
The code, updated with the above mentioned points 1 and 2 would be similar to this:
var allFs = fRepository.GetFs().Select(f => new {f.Name, f.SerialNumber}).ToList();
int year = Convert.ToInt32(billingYear);
int month = Convert.ToInt32(billingMonth);
var allEs = eRepository.GetEs().Where(e.Year == year && e.Month == month).Select(e => new {e.FSerialNumber, e.IntCustID}).ToList();
var EFs = from c in allFs
join e in allEs on c.SerialNumber equals e.FSerialNumber
select new EReport
{
FSerialNumber = c.SerialNumber,
FName = c.Name,
IntCustID = Convert.ToInt32(e.IntCustID),
TotalECases = 0,
TotalPrice = "$0"
};
I have the following linq query:
var solicitudes = from s in dbContext.Menores
select s.Solicitud.fiExpEmpleado;
The query results are 41 employees' Ids. My question is, how can I compare these 41 elements against the value of a textbox so that i can restrict user registration (if the ID of the textbox matches with one of the query result the registration is denied)?
Hope your help.
You can write a query that checks whether the value exists:
if (dbContext.Menores.Any(s => s.Solicitud.fiExpEmpleado == someValue))
string text = textbox.Text.Trim();
var solicitudes = (from s in dbContext.Menores
where s.FieldToCheck == text
select s.Solicitud.fiExpEmpleado).FirstOrDefault();
if (solicitudes != null)
{
//Deny
}
If solicitudes is being returned as a list of ints you could just to:
int employeeId = Convert.ToInt32(txtMyTextBox.Text);
bool isValidEmployeeId = solicitudes.Any(employeeId);
You don't have to compare all values, just create linq query which query for the value of the textbox, and then count use count method,if count is greater then zero, it means it exits,and you can then deny the user.
Here you go.
if (dbContext.Menores.Exists(x => x.FieldToCheck == text))
{
//deny
}