Lambda expression with separate column values - c#

I am trying to get a a query to work with user input. I am new to C# and lambdas so sorry for the basic question but I have hit a road block. I am getting an address input from a user in separate fields, 5 separate fields to be exact.
if (!string.IsNullOrEmpty(SessionHandler.StreetNumber))
{
allFeatures = layerFindResults.QueryTools.GetAllFeatures(ReturningColumnsType.AllColumns);
searchResults = allFeatures.Where(f => f.ColumnValues["STREETNUM"].ToLower().Contains(SessionHandler.StreetNumber.ToLower()).Select(f =>new
{
StreetNum = f.ColumnValues["STREETNUM"],
StreetName = f.ColumnValues["STR_NAME"]
}).ToList());
}
This works for getting the values in STREETNUM but i am wondering if there is a way to get other values that are associated with that column value such as Street name without the user inputting a value for them.
If this is unclear, I am sorry.

if there is a way to get other values that are associated
The Select is your friend. Select creates a projection meaning one is changing from one form of data to another. What you want to do is create a dynamic entity using the Select where you extract the related/needed data such as here where it returns the city as well:
searchResults
= allFeatures.Where( ... )
.Where( ... ) // Behaves like an `and` between the two where's.
.Select(f => new
{
Street = f.ColumnValues["STREETNUM"],
City = f.ColumnValues["City"]
})
.ToList();

I'm sure there's a way to do this with .Where() and a lambda expression, but IMO you can't beat the LINQ "SQL-like" syntax, i.e.,
searchResults = (from DataType i in allFeatures where f.StreetNum = SessionHandler.StreetNum select i).ToList(); //returns a list of matching objects

Related

Check if text contains any string item from list of string c# linq

I am trying to fetch a list of users after filtering by their name.
Query:
string filter="alex, faheem, Cohen";
var filterArr=filter.Split(new []{','},StringSplitOptions.RemoveEmptyEntries).Select(f=>f.Trim()).ToList();
var users= (from u in DbContext.Users
where filterArr.Any(y=> u.Name.Contains(y)) select u);
This gives me the error:
Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.
I can't use filterArr.Contains(x.Name) because Name column contains both first name and second name. Just Like in list above their is an item "alex" and I have a name "Alex Hales" combined in Name column. So If I use filterArr.Contains(x.Name) it will not give me the result.
Any help will be much appreciated.
I'm not sure this is possible in a single statement like this. It's too complicated for the poor parsing stuff to work out.
However, you can get an IQueryable(), then iterate over your filters append these as individual WHERE clauses, then these should get added to the SQL properly later.
Something like this:
//this just gets a reference the DbSet, which implements IQueryable<User>
var queryable = _dbContext.Users;
//iterate over the filters and add each as a separate WHERE clause
foreach(var f in filters)
{
//this just adds to the existing expression tree..
queryable = queryable.Where(u=>u.Name.Contains(f));
}
//this will actually hit the database.
var results = queryable.ToList();
This should generate something like this in SQL (entirely pseudo-code)
select
u.*
from
users u
where
(u.username like "%Sue%")
or (u.username like "%Bob%")
Hope this helps...
I think you can do something like this
string filter = "alex, faheem, Cohen";
var filterArr = filter.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(f => f.Trim()).ToList();
var users = _dbContext.Users.Where(x => filterArr.Any(n => n.Contains(x.Name))).ToList();
UPDATE
For your requirement following query will work fine.
string filter = "Alex, faheem, Cohen";
var filterArr = filter.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(f => f.Trim())
.ToList();
var users = _dbContext.Users
.Where(x => filterArr.Any(n => x.UserName.Contains(n))).ToList();
If user has searched for "alex" and in Name (database column) there is "Alex Hales". users query will return the user "Alex Hales".

ASP.NET MVC C# Select and Where Statements

I'm having trouble understanding .Select and .Where statements. What I want to do is select a specific column with "where" criteria based on another column.
For example, what I have is this:
var engineers = db.engineers;
var managers = db.ManagersToEngineers;
List<ManagerToEngineer> matchedManager = null;
Engineer matchedEngineer = null;
if (this.User.Identity.IsAuthenticated)
{
var userEmail = this.User.Identity.Name;
matchedEngineer = engineers.Where(x => x.email == userEmail).FirstOrDefault();
matchedManager = managers.Select(x => x.ManagerId).Where(x => x.EngineerId == matchedEngineer.PersonId).ToList();
}
if (matchedEngineer != null)
{
ViewBag.EngineerId = new SelectList(new List<Engineer> { matchedEngineer }, "PersonId", "FullName");
ViewBag.ManagerId = new SelectList(matchedManager, "PersonId", "FullName");
}
What I'm trying to do above is select from a table that matches Managers to Engineers and select a list of managers based on the engineer's id. This isn't working and when I go like:
matchedManager = managers.Where(x => x.EngineerId == matchedEngineer.PersonId).ToList();
I don't get any errors but I'm not selecting the right column. In fact the moment I'm not sure what I'm selecting. Plus I get the error:
Non-static method requires a target.
if you want to to select the manager, then you need to use FirstOrDefault() as you used one line above, but if it is expected to have multiple managers returned, then you will need List<Manager>, try like:
Update:
so matchedManager is already List<T>, in the case it should be like:
matchedManager = managers.Where(x => x.EngineerId == matchedEngineer.PersonId).ToList();
when you put Select(x=>x.ManagerId) after the Where() now it will return Collection of int not Collection of that type, and as Where() is self descriptive, it filters the collection as in sql, and Select() projects the collection on the column you specify:
List<int> managerIds = managers.Where(x => x.EngineerId == matchedEngineer.PersonId)
.Select(x=>x.ManagerId).ToList();
The easiest way to remember what the methods do is to remember that this is being translated to SQL.
A .Where() method will filter the rows returned.
A .Select() method will filter the columns returned.
However, there are a few ways to do that with the way you should have your objects set up.
First, you could get the Engineer, and access its Managers:
var engineer = context.Engineers.Find(engineerId);
return engineer.Managers;
However, that will first pull the Engineer out of the database, and then go back for all of the Managers. The other way would be to go directly through the Managers.
return context.Managers.Where(manager => manager.EngineerId == engineerId).ToList();
Although, by the look of the code in your question, you may have a cross-reference table (many to many relationship) between Managers and Engineers. In that case, my second example probably wouldn't work. In that case, I would use the first example.
You want to filter data by matching person Id and then selecting manager Id, you need to do following:
matchedManager = managers.Where(x => x.EngineerId == matchedEngineer.PersonId).Select(x => x.ManagerId).ToList();
In your case, you are selecting the ManagerId first and so you have list of ints, instead of managers from which you can filter data
Update:
You also need to check matchedEngineer is not null before retrieving the associated manager. This might be cause of your error
You use "Select" lambda expression to get the field you want, you use "where" to filter results

Creating a single Type from muliple entities in Lambda

I have 3 entities
I'd like to flatten the tblCondition and BusinessAreas into one object. What I want is Category.ID, Category.Category, BusinessArea.ID, BusinessArea AreaName.
I know this can be done by creating an Anonymous type with Lambda but I'm relatively unskilled with Lampda or LINQ.
Forgot to mention that I need to get to the two tables through the first one.
My original call looks like this.
myConditionTemplate = EE.ConditionTemplates.Where(c => c.TemplateCode == TextBoxSearchConditionCode.Text).FirstOrDefault();
Here's the official documentation: http://msdn.microsoft.com/en-us/library/vstudio/bb384105.aspx
Essentially in your select portion use the new keyword without a class name like:
select new { Category.ID, Category.Category, BusinessArea.ID, BusinessArea.AreaName }
The webpage only shows an example using Linq in query form, but to do it in method form:
var results = db.GetStuff().Select(x => new { x.ID, x.Name });
Ack, that may not be very clear. I just found some great examples at How to do a join in linq to sql with method syntax?. This was a different question, but the answer's example shows you how to do the lamba for a joined enumerable set.
UPDATE: Since you updated your question, see if this helps:
var results = myConditionTemplate.Select(x => new { CategoryID = x.tblCondition.ID, Category = x.tblCondition.Category, BusinessAreaID = x.tblCondition.BusinessArea.ID, AreaName = x.tblCondition.BusinessArea.AreaName});

Distinct elements in LINQ

I have a situation where i display a list of products for a customer. So, there are two kinds of products. So, if customer is registerd to two products, then both the products get displayed. So, I need to display distinct rows. I did this:
var queryProducts = DbContext.CustomerProducts.Where(p => p.Customers_Id ==
customerID).ToList().Select(r => new
{
r.Id,
r.Products_Id,
ProductName = r.Product.Name,
ShortName = r.Product.ShortName,
Description = r.Product.Description,
IsActive = r.Product.IsActive
}).Distinct();
In this, customerID is the value that i get from dropdownlist. However, it still displays the same row twice. So, can you please let me know how i can display only distinct records.
The most likely reasons could be that Distinct when called with no parameter by default compares all the public properties for equality. I suspect your Id is going to be unique. Hence the Distinct is not working for you.
You can try something like
myCustomerList.GroupBy(product => product.Products_Id).Select(grp => grp.First());
I found this as answers to
How to get distinct instance from a list by Lambda or LINQ
Distinct() with lambda?
Have a look at LINQ Select Distinct with Anonymous Types
I'm guessing r.ID is varying between the two products that are the same, but you have the same Products_Id?
You can write an implementation of IEqualityComparer<CustomerProduct>. Once you've got that, then you can use this:
DbContext.CustomerProducts.Where(p => p.Customers_Id == customerId)
.ToList()
.Distinct(new MyComparer())
.Select(r => new {
// etc.
public class MyComparer : IEqualityComparer<CustomerProduct>
{
// implement **Equals** and **GetHashCode** here
}
Note, using this anonymous comparer might work better for you, but it compares all properties in the anonymous type, not just the customer ID as specified in the question.

Numbering the rows per group after an orderby in LINQ

Say you have columns AppleType, CreationDate and want to order each group of AppleType by CreationDate. Furthermore, you want to create a new column which explicitly ranks the order of the CreationDate per AppleType.
So, the resulting DataSet would have three columns, AppleType, CreationDate, OrderIntroduced.
Is there a LINQ way of doing this? Would I have to actually go through the data programmatically (but not via LINQ), create an array, convert that to a column and add to the DataSet? I have there is a LINQ way of doing this. Please use LINQ non-method syntax if possible.
So are the values actually appearing in the right order? If so, it's easy - but you do need to use method syntax, as the query expression syntax doesn't support the relevant overload:
var queryWithIndex = queryWithoutIndex.Select((x, index) => new
{
x.AppleType,
x.CreationDate,
OrderIntroduced = index + 1,
});
(That's assuming you want OrderIntroduced starting at 1.)
I don't know offhand how you'd then put that back into a DataSet - but do you really need it in a DataSet as opposed to in the strongly-typed sequence?
EDIT: Okay, the requirements are still unclear, but I think you want something like:
var query = dataSource.GroupBy(x => x.AppleType)
.SelectMany(g => g.OrderBy(x => x.CreationDate)
.Select((x, index ) => new {
x.AppleType,
x.CreationDate,
OrderIntroduced = index + 1 }));
Note: The GroupBy and SelectMany calls here can be put in query expression syntax, but I believe it would make it more messy in this case. It's worth being comfortable with both forms.
If you want a pure Linq to Entities/SQL solution you can do something like this:
Modified to handle duplicate CreationDate's
var query = from a in context.AppleGroup
orderby a.CreationDate
select new
{
AppleType = a.AppleType,
CreationDate = a.CreationDate,
OrderIntroduced = (from b in context.AppleGroup
where b.CreationDate < a.CreationDate
select b).Count() + 1
};

Categories