Composable LINQ Select Clause - linq

Is there a way to build on to the select clause of a previously defined LINQ query?
For example:
var stuffQuery =
from stuff in MyStuff
select new {
stuff.Name
};
var query2 =
from stuff in stuffQuery
join otherStuff in YourStuff on stuff.Name equals otherStuff.Name
select new {
stuff.*, // how can I accomplish this?
YourStuff = new {
otherStuff.PropertyX
}
};
The result I want is an object like:
string Name
anonymous YourStuff
string PropertyX
I thought about using a "Combine" method which would reflectively combine my two anonymous objects into a dynamic. But Linq-to-Sql won't know what to do with the method.
Instead, I think I need a method which returns the select expression. Its parameters would be the first Queryable, and the select expression for the second Queryable. Something like:
var query2 =
from stuff in stuffQuery
join otherStuff in YourStuff on stuff.Name equals otherStuff.Name
GetCombinedSelectClause(stuffQuery, new {
YourStuff = new {
otherStuff.PropertyX
}
});
How can I accomplish this? I'm not married to any particular syntax-style. However, I'd prefer not to use a string-based solution (such as System.Linq.Dynamic).

How about ExpandoObject? I believe it can do exactly what you need.

My question probably isn't worded the best it could be. However, I do not think LINQ queries were designed to accomplish the goal I was after.
I'm closing the question because I simply do not think the answer is achievable.

Related

Returning a list using LINQ

I want to return a list of objects stored in a database using LINQ queries.
I tried the following
public BO.Hotel getHotels()
{
TripBagEntities db = new TripBagEntities();
var hotels = (from m in db.HotelEntities
where m.id < 10
select m).ToList().First();
return Mapper.ToHotelObject(hotels);
}
This returns only the first item in the list. How can I return the entire list?
Thanks in advance
Firstly, as per the comment, you should understand exactly what each line of your existing code does first. (You should also try to follow .NET naming conventions.) If you're guessing around which bit of your code does what, it would be a good idea to read a good tutorial geared towards the LINQ provider you're using (Entity Framework?).
We don't really know what Mapper.ToHotelObject does, or whether there's already a method for converting a whole sequence. This should work though:
public List<BO.Hotel> GetHotels()
{
// Note: you may want a using statement here...
TripBagEntities db = new TripBagEntities();
var hotels = db.HotelEntities
.Where(m => m.id < 10)
.AsEnumerable()
.Select(Mapper.ToHotelObject)
.ToList();
}
Or if the method group conversion doesn't work:
public List<BO.Hotel> GetHotels()
{
// Note: you may want a using statement here...
TripBagEntities db = new TripBagEntities();
var hotels = db.HotelEntities
.Where(m => m.id < 10)
.AsEnumerable()
.Select(m => Mapper.ToHotelObject(m))
.ToList();
}
Note that I've used "dot notation" for the whole query, as it makes life simpler when you're using things like AsEnumerable and ToList, and your query expression wasn't complicated anyway.
The AsEnumerable call "shifts" the query into LINQ to Objects, so that the query-to-SQL translation part doesn't need to try to convert Mapper.ToHotelObject into SQL, which I assume would fail.
You need to make your function return List<BO.Hotel> instead of a Hotel, and adjust your query and Mapper function accordingly.
public List<BO.Hotel> getHotels()
{
TripBagEntities db = new TripBagEntities();
return (from m in db.HotelEntities
where m.id < 10
select Mapper.ToHotelObject(m)).ToList();
}

Nhibernate linq. The where extension method does not add the where clause to the SQL command, why?

I want to add the where clause to a linq statement, but it doesn't behave as i would expected it to.
When i use this code:
IQueryable<Employee> EmpQuery = from e in Session.Query<Employee>() where e.Surname == "Test" select e;
EmpQuery.ToList();
or i use this code:
IQueryable<Employee> EmpQuery = (from e in Session.Query<Employee>() select e).Where(e => e.Surname == "Test");
EmpQuery.ToList();
The where clause is included in the SQL command, but when i try it this way:
IQueryable<Employee> EmpQuery = from e in Session.Query<Employee>() select e;
EmpQuery.Where(e => e.Surname == "Test");
The where clause is not included in the SQL command. Why is this? Is there another way to dynamically add criteria to a Nhibernate Linq query?
You're not using the return value of Where. LINQ is designed around functional concepts - calling Where doesn't modify the existing query, it returns a new query which applies the filter. The existing query remains as it was - which means you can reuse it for (say) a different filter.
Note that your current query expression (from x in y select x, effectively) is pretty pointless. I would suggest simply writing:
var query = Session.Query<Employee>().Where(e => e.Surname == "Test");
Just to clarify on Jon's remark, your implementation would be fine with the following tweak:
IQueryable<Employee> modifiedQuery = EmpQuery.Where(e => e.Surname == "Test");
Then just invoke the appropriate enumerator (ToList, ToArray, foreach) on modifiedQuery. And I wouldn't say that it create a complete new query, but instead creates a query which wraps around the original (kind of along the lines of the adapter pattern). Granted, your example doesn't need the additions, but this is how you would add additional criteria onto an existing LINQ expression, and that is what your question actually asked.

Like condition in LINQ

I am relatively new to LINQ and don't know how to do a Like condition. I have an IEnumerable list of myObject and want to do something like myObject.Description like 'Help%'. How can I accomplish this? Thanks
Look here:
http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/16/linq-to-sql-like-operator.aspx
Snippet:
StartsWith and Contains:
var query = from c in ctx.Customers
where c.City.StartsWith("L") && c.City.Contains("n")
select c;
And if you should use it with LINQ to SQL (does not work with LINQ to Objects):
Custom LIKE (System.Data.Linq.SqlClient.SqlMethods.Like):
var query = from c in ctx.Customers
where SqlMethods.Like(c.City, "L_n%")
select c;
You generally use the exact same syntax you'd use outside a query.
myObject.Description.StartsWith("Help")
Whether this actually works depends on where you're using LINQ (it might either be ran as code, in which case everything works, or get converted to something like else, such as SQL, which might have limitations), though, but it's always worth a try.
You can use StartsWith, EndsWith, or Contains depending where you want to check:
var result = from o in myCollection
where o.Description.StartsWith("Help")
select o;
You can optionally pass a StringComparison to specify whether to ignore case or not (for StartsWith and EndsWith) which would make the operation behave more like a SQL query:
var result =
from o in myCollection
where o.Description
.StartsWith("Help", StringComparison.InvariantCultureIgnoreCase))
select o;
If you want to do a case insensitive contains, you need to use IndexOf instead:
var result =
from o in myCollection
where o.Description
.IndexOf("Help", StringComparison.InvariantCultureIgnoreCase) > 0
select o;
you can use string.StartsWith or string.EndsWith or string.Contains property of string to use it as Like Operator.
Startswith will work for Like 'A%'
Endswith will work for Like '%A'
Contains will work like '%A%'

How do I use Like in Linq Query?

How I can use Like query in LINQ ....
in sql for eg..
name like='apple';
thanks..
Use normal .NET methods. For example:
var query = from person in people
where person.Name.StartsWith("apple") // equivalent to LIKE 'apple%'
select person;
(Or EndsWith, or Contains.) LINQ to SQL will translate these into the appropriate SQL.
This will work in dot notation as well - there's nothing magic about query expressions:
// Will find New York
var query = cities.Where(city => city.Name.EndsWith("York"));
You need to use StartsWith, Contains or EndsWith depending on where your string can appear. For example:
var query = from c in ctx.Customers
where c.City.StartsWith("Lo")
select c;
will find all cities that start with "Lo" (e.g. London).
var query = from c in ctx.Customers
where c.City.Contains("York")
select c;
will find all cities that contain "York" (e.g. New York, Yorktown)
Source
name.contains("apple");
I use item.Contains("criteria"), but, it works efficiently only if you convert to lower both, criteria and item like this:
string criteria = txtSearchItemCriteria.Text.ToLower();
IEnumerable<Item> result = items.Where(x => x.Name.ToLower().Contains(criteria));

Linq - How to query specific columns and return a lists

I am trying to write a linq query that will only return certain columns from my entity object into a list object.
Below is my code which produces an error(can't implicitly convert a generic list of anonymous types to a generic list of type TBLPROMOTION):
IQueryable<TBLPROMOTION> matches = webStoreContext.TBLPROMOTION.Include("TBLSTORE").Include("LKPROMOTIONTYPE");
List<TBLPROMOTION> promotionInfo = null;
promotionInfo = (from p in matches
orderby p.PROMOTION_NM descending
select new { p.EFFECTIVE_DT, p.EXPIRE_DT, p.IS_ACTIVE,
p.PROMOTION_DESC, p.PROMOTION_ID, p.PROMOTION_NM }).ToList();
What would be the best way to accomplish this. I do not want to do a "select p" in this case and return all the columns associated with the query.
thanks in advance,
Billy
Can't you do var promotionInfo = () and get a list of anonymous types?
Okay, basically you can not cast an Anonymous type to a known type like TBLPROMOTION.
ofcourse, you can say var promotionInfo = and then get an IEnumerable<{Anonymoustype}> and use that to do, what you were wanting to do with promotionInfo.
Also, personally I prefer the Fluent version of a linq query, easy on the eyes, good programming diet, at least for me :)
var promotionInfo = matches
.OrderByDescending( p => p.PROMOTION_NM)
.Select( p => new { p.EFFECTIVE_DT,
p.EXPIRE_DT,
p.IS_ACTIVE,
p.PROMOTION_DESC,
p.PROMOTION_ID,
p.PROMOTION_NM})
.ToList();
If you're moving from a L2E query to a Type already defined, you may need a step between. I haven't tried to compile this but something like:
List<TBLPROMOTION> promotions = new List<TBLPROMOTION>();
var results = from p in matches
orderby p.PROMOTION_NM descending
select new
{
p.EFFECTIVE_DT,
p.EXPIRE_DT,
p.IS_ACTIVE,
p.PROMOTION_DESC,
p.PROMOTION_ID,
p.PROMOTION_NM
};
foreach (var v in results)
{
promotions.Add(new TBLPROMOTION(v.EFFECTIVE_DT, v.EXPIRE_DT, v.IS_ACTIVE,
v.PROMOTION_DESC, v.PROMOTION_ID, v.PROMOTION_NM));
}
Based on the comment below, you might try something like:
foreach(var v in results)
{
TBLPROMOTION temp = new TBLPROMOTION();
temp.EFFECTIVE_DT = v.EFFECTIVE_DT;
temp.EXPIRE_DT = v.EXPIRE_DT;
temp.IS_ACTIVE = v.IS_ACTIVE
// Assign Other Properties
promotions.Add(temp);
}
.......
Sorry: Just read the addition to the top.
Are you sure that none of the fields you're leaving out (instead of saying "select p") are required for a TBLPROMOTION object? Also, sense your TBLPROMOTION object is going to have properties (and therefore memory allocated) for those skipped fields, why not just use an annonymous type or set up a helper class that contains only your needed properties?
#Billy, following code worked for me.
List<TBLPROMOTION> promotionInfo =
(from p in matches
orderby p.PROMOTION_NM descending
select new TBLPROMOTION(p.EFFECTIVE_DT, p.EXPIRE_DT, p.IS_ACTIVE,
p.PROMOTION_DESC, p.PROMOTION_ID, p.PROMOTION_NM)
).ToList();
did you try
select new TBLPROMOTION {.....
instead of
select new {.....
List<TBLPROMOTION> promotionInfo = null;
promotionInfo = (from p in matches
orderby p.PROMOTION_NM descending
select new TBLPROMOTION { COL1 = p.EFFECTIVE_DT, COL2 = p.EXPIRE_DT, COL3 = p.IS_ACTIVE... }).ToList();
Where COL1, COL2, ... are the names of the properties on TBLPROMOTION you wish you populate.
If you want a subset of the table you have 2 options:
#Fredou mentioned select new TBLPROMOTION{...}
other way is to create a custom DTO which has the exact properties & select them instead like:
List promotionInfo = ...
select new TBLPROMOTION_DTO{
Effective_dt = ...
}
HTH

Resources