i want to select from 2 different objects in Linq in order to compare them. This is what i tried,
var myItem = (from abc in firstList.Value
from cds in secondList
where (abc.Key.theKey == cds.secondList.theSecondKey
select cds).SingleOrDefault();
although i get an error:
Type inference failed in the call to 'SelectMany'
If that's your exact query, it may just be because you've got unmatched brackets. Try this:
var myItem = (from abc in firstList.Value
from cds in secondList
where abc.Key.theKey == cds.secondList.theSecondKey
select cds).SingleOrDefault();
Admittedly I would probably rewrite that using a join - in most cases the join will be more efficient.
However, if that's not your exact query, please post a short but complete program which demonstrates the problem. It's not clear why cds would have a secondList property for example. A complete example demonstrating the problem would make this a lot simpler.
You have an opening paranthesis in more:
var myItem = (from abc in firstList.Value
from cds in secondList
where abc.Key.theKey == cds.secondList.theSecondKey
select cds
).SingleOrDefault();
Related
The syntax given for contains clause is
ids = new int[] {1,2,3,4};
dataContext.Table.Where("#0.Contains(id)", ids);
But what I want is
dataContext.Table.Where("{1,2,3,4}.Contains(id)"); //getting exception here
[ERROR] Expression expected (at index 0)
I need this because the where clause my or may not use the contains method. it depends on how user acts.
so I got the answer for this after tinkering for sometime. So posting the answer here.
dataContext.Table.Where("new Int[]{1,2,3,4}.Contains(id)");
You can use whatever datatype you need. I use reflection to find datatype and use that accordingly.
try code:
int[] ids= {1,2,3,4};
dataContext.Table.Where(c=>c.ids.Contains(t.id)).ToList();
Or
var result= (from p in dataContext.Table.AsEnumerable()
join q in ids on p.id equals q
select p).Distinct() .ToList();
Suppose I have a list of {City, State}. It originally came from the database, and I have LocationID, but by now I loaded it into memory. Suppose I also have a table of fast food restaurants that has City and State as part of the record. I need to get a list of establishments that match city and state.
NOTE: I try to describe a simplified scenario; my business domain is completely different.
I came up with the following LINQ solution:
var establishments = from r in restaurants
from l in locations
where l.LocationId == id &&
l.City == r.City &&
l.State == r.State
select r
and I feel there must be something better. For starters, I already have City/State in memory - so to go back to the database only to have a join seems very inefficient. I am looking for some way to say {r.City, r.State} match Any(MyList) where MyList is my collection of City/State.
UPDATE
I tried to update based on suggestion below:
List<CityState> myCityStates = ...;
var establishments =
from r in restaurants
join l in myCityStates
on new { r.City, r.State } equals new { l.City, l.State } into gls
select r;
and I got the following compile error:
Error CS1941 The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.
UPDATE 2
Compiler didn't like anonymous class in the join. I made it explicit and it stopped complaining. I'll see if it actually works in the morning...
It seems to me that you need this:
var establishments =
from r in restaurants
join l in locations.Where(x => x.LocationId == id)
on new { r.City, r.State } equals new { l.City, l.State } into gls
select r;
Well, there isn't a lot more that you can do, as long as you rely on a table lookup, the only thing you can do to speed up things is to put an index on City and State.
The linq statement has to translate into a valid SQL Statement, where "Any" would translate to something like :
SELECT * FROM Restaurants where City in ('...all cities')
I dont know if other ORM's give better performance for these types of scenarios that EF, but it might be worth investigating. EF has never had a rumor for being fast on reads.
Edit: You can also do this:
List<string> names = new List { "John", "Max", "Pete" };
bool has = customers.Any(cus => names.Contains(cus.FirstName));
this will produce the necessary IN('value1', 'value2' ...) functionality that you were looking for
Setup
I have two List<T>'s.
The data is un-normalized and from different sources which explains the convolution in the desired logic
An informal compound key in the data is fieldA, fieldB, fieldC.
The "fields" are strings - reference types - so their values could be null. I want to drop records where they may be matching on null. I get that null references in C# will match, but in SQL they do not. Adding a !string.IsNullOrEmpty() is easy enough.
This is not a question about DB design or relational algebra.
I have other logic which covers other criteria. Do not suggest reducing the logic shown such that it might broaden the result set. See # 5 above.
The Problem
I want to find the records in listA that are not in listB based on the informal key. I then want to further refine the listA results based on a partial key match.
The SQL version of the problem:
select
listA.fieldA, listA.fieldB, matching.fieldC
from listA
left join listB keyList on
listA.fieldA = keyList.fieldA and
listA.fieldB = keyList.fieldB and
listA.fieldC = keyList.fieldC
inner join listB matching on
listA.fieldA = matching.fieldA and
listA.fieldB = matching.fieldB
where
keyList.fieldA is null
SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)
Note: IN and NOT IN use the same function in the LINQ query, but it just use a ! (not) symbol for it. Here is the graphical representation:
You use, where <list>.Contains( <item> )
var myProducts = from p in db.Products
where productList.Contains(p.ProductID)
select p;
Or you can have a list predefined as such:
var ids = {1, 2, 3};
var query = from item in context.items
where ids.Contains( item.id )
select item;
For the 'NOT' case, just add the '!' operator before the 'Contains' statement.
I've been trying to solve this for the entire day.. :-(
I'm Using C# with MSSQL and querying via LINQ
I have a collection stored in studWithTuiDisc variable, It contains the following data (shown in the link below)
(source: secompeusc.com)
When using this variable as reference for other LINQ Statements the results are very off, prior to this post I performed experiments to check if it really wasn't my fault that incorrect results were returned:
(1) I tried to iterate through studWithTuiDisc and then checking the relationship only in the select clause since I'm sure that this will return the desired output (see below)
Code:
var xxx = (from a in studWithTuiDisc
select new
{
please = a.StudentId,
help = _conn.EEnrolledSubjects
.Where(m => m.StudentId == a.StudentId)
.Select(m => m.StudentId)
.FirstOrDefault()
}).Distinct();
Output:
(source: secompeusc.com)
As we can see the studWithTuiDisc values are the only values contained in xxx
(2) Now I tried the approach that gave me a lot of headaches (see below)
Code:
var zzz = (from a in studWithTuiDisc
join b in _conn.EEnrolledSubjects on a.StudentId equals b.StudentId
select new { please = a.StudentId, help = b.StudentId }).Distinct();
or
var zzz = (from a in studWithTuiDisc
from b in _conn.EEnrolledSubjects
where a.StudentId == b.StudentId
select new { please = a.StudentId, help = b.StudentId }).Distinct();
Output:
(source: secompeusc.com)
Given that we already know the values in studWithTuiDisc and since we used it as filter for _conn.EEnrolledSubjects we should be expecting results that are in studWithTuiDisc but looking at the screen shots, LINQ is not returning the proper results.
What am I doing wrong?
Has anyone experienced something like this before?
Does anyone know why this is happening?
Check what is generated/sent to SQL Server by using DataContext.Log, or SQL Profiler. I think that your queries will be different.
I want to build a dlinq query that checks to see if a title has any number of items in it. I know you can do .Contains() with a list, but I need to check if the title contains any of the items, not if the items contain part of the title. For example: I have three items in the list "bacon, chicken, pork". I need the title of "chicken house" to match.
var results = (from l in db.Sites
where list.Contains(l.site_title)
select l.ToBusiness(l.SiteReviews)).ToList();
If I try the first 2 answers, I get an error "Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator."
The third solution gives me
Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL."
Try the following. You can use a combination of Where and Any to search for substring matches.
var results = (from l in db.Sites
where list.Where(x => 0 != x.IndexOf(l)).Any()
select l.ToBusiness(l.SiteReviews)).ToList();
One way is to dynamically build a query as outlined here:
http://andrewpeters.net/2007/04/24/dynamic-linq-queries-contains-operator/
I finally figured it out. Thanks to my good buddy Cory for the help. There are two ways you can do it.
var resultSets = (from k in list
select (from b in db.Sites
where b.site_title.Contains(k)
select b.ToBusiness()).ToList<Business>()).ToList();
List<Business> all = new List<Business>();
for (int i = 0; i < resultSets.Count; ++i)
{
all.AddRange(resultSets[i]);
}
This is a linq query that will successfuly do what is stated. As well, you can also just build the sql query in plain text by hand.