I have these two tables.
var cardtagtable = (from u in db.CardTagTables
where u.FKCardTagID == cardtable.cardID
select u.CardTagName).ToList();
var tagtable = (from u in db.TagTables
select u.TagName).ToList();
Where in cardtagtable all names are selected to match with tagtable's name.
Condition-
I want names from tagtable except names coming from cardtagtable list.
so I tried here-
var list = tagtable.Except(cardtagtable);
This list is a sequence of all names except from cardtagtable.
Everything is all right till now.
Now I will use this list and pass it through the model.
var taglist = (from u in list
select new TagModel {
tagId = u.TagID,
tagName = u.TagName,
tagCount = Convert.ToInt32(u.TagCount) == null ? 0 : Convert.ToInt32(u.TagCount),
}).ToList();
But this query says me no definition found for Model values from u.
How do I use this list here in this case?
Because u is probably a string because your list is a IEnumerable<string>.The reason is that you are only selecting your TagNames, so your list contains only tag names, not your TagTables.Instead you need to select your elements instead of just tag names:
var cardtagtable = (from u in db.CardTagTables
where u.FKCardTagID == cardtable.cardID
select u).ToList();
var tagtable = (from u in db.TagTables
select u).ToList();
Then use Where and Any instead of Except like this:
var list = tagtable.Where(c => !cardtagtable
.Any(x => x.CardTagName == c.TagName));
Then your last query should work fine.
Update: Also there is a more elegant and optimized way to do that (especially if this is LINQ to SQL).You can select only CardtagNames from cardtagtable and use Contains method:
var cardtagtable = (from u in db.CardTagTables
where u.FKCardTagID == cardtable.cardID
select u.CardTagName).ToList();
var tagtable = (from u in db.TagTables
select u).ToList();
var list = tagtable.Where(c => !cardtagtable.Contains(c.TagName));
Related
I want to drill down into a particular item in my data and output the list of results to the output window. My query result looks like this
private IEnumerable<DataRow> _data;
var query = from data in this._data
group data by data.Field<string>("Form Name") into groups //same as Form ID
select new
{
formName = groups.Key,
items = from d in groups
group d by d.Field<string>("Item Name") into grps
let name = grps.Key
let documentIDGroups = grps.GroupBy(t => t.Field<string>("Document ID"))
let documentIDGroupsCount = documentIDGroups.Count()
let distinctDocumentValueCount = from data in documentIDGroups
select new
{
docID = data.Key,
distinctDocValueCount = data.Where(t => string.IsNullOrEmpty(t.Field<string>("Document Value").Trim()) == false).Select(t => t.Field<string>("Document Value")).Distinct().Count()
}
let sum = distinctDocumentValueCount.Sum(t => t.distinctDocValueCount)
let distinctItemsNames = from data in grps
select data.Field<string>("Item Name").Distinct().Count()
let count = distinctItemsNames.Count()
select new
{
itemName = name,
documentIDGroups,
documentIDGroupsCount,
averageChoices = Math.Round(((decimal)sum / documentIDGroupsCount), 2),
distinctDocumentValueCount,
sum
}
};
So on that query result I want to drill down into a particular form name, and from there get a particular Item Name and so on
so the first step is to get the grouping of items and I have
var items = from d in query where d.formName == "someName" select d.items;
but I don't know how to isolate the items by a particular string.
I want to do the following
var item = from d in items where d.itemName == "anItemName" select d;
But I don't know the syntax.
Use the .FirstOrDefault extension if you expect a single item to be returned from your query. SO:
var item = (from d in items where d.itemName == "anItemName" select d).FirstOrDefault();
I am trying to link up the RestaurantId in the RestaurantReservationEventsTbl with the RestaurantID in the RestaurantTbl to display reservations that are only made for the currently logged in restaurant.
I am receiving the following error in my code operator == cannot be applied to operands of type int and iqueryable int
Here is what I am doing in my home controller
var RestaurantIDRestaurantTbl = from r in db.Restaurants select r.RestaurantID;
//var listOfRestaurantsReservations = db.RestaurantReservationEvents.ToList();
var listOfRestaurantsReservations = db.RestaurantReservationEvents.Where(x => x.RestaurantID == RestaurantIDRestaurantTbl).ToList();
//return View(restaurants.Where(x => x.RestaurantEmailAddress == UserEmail).ToList());
//create partial view called _RestaurantReservation
return PartialView("_RestaurantReservations", listOfRestaurantsReservations);
You have to change your code to materialize the restaurantIds like this:
var RestaurantIDRestaurantTbl = (from r in db.Restaurants
select r.RestaurantID).ToList();
Then you may change the code as below for the comparison to work:
var listOfRestaurantsReservations = db.RestaurantReservationEvents.Where(x => RestaurantIDRestaurantTbl.Contains(x.RestaurantID)).ToList();
Anyway this is not the best solution. I will write another example for you, just try this example if it is working or not and let me know for the result.
I would considering changing the code as below to be much more efficient:
var listOfRestaurantsReservations = (from r in db.Restaurants
join e in db.RestaurantReservationEvents
on r.RestaurantID equals e.RestaurantID
//where r.RestaurantID == something //if where condition needed
select e).ToList();
If your tables are not connected with foreignkeys please consider to read this documentation here to make a better structure of the tables since they are related to each-other.
If your tables are related as in documentation article you might have something like that:
var RestaurantIDRestaurantTbl = db.Restaurants.SingleOrDefault(x => x.RestaurantID == something);
if(RestaurantIDRestaurantTbl != null)
{
var listOfRestaurantsReservations = RestaurantIDRestaurantTbl.RestaurantReservationEvents.ToList();
}
{
// This will give you a list of IDs
var RestaurantIDRestaurantTbl = db.Restaurants
.Select(p => p.RestaurantID)
.ToList();
// Using .Any() is a better choice instead of .Contains()
// .Contains is used to check if a list contains an item while .Any will look for an item in a list with a specific ID
var listOfRestaurantsReservations = db.RestaurantReservationEvents
.Where(p => RestaurantIDRestaurantTbl.Any(r => r.pRestaurantID == p))
.ToList();
}
In the code below, profile is a string. I would like to know how to write a query in case where profile is a string array or list. ie the array or list can have multiple elements like { 'Profile1','profile2'}
var ccData = (from p in db.ChannelContacts where p.ProfileId == profile select p);
You could use an efficient join:
var ccData = from p in db.ChannelContacts
join profileID in profiles // your collection
on p.ProfileId equals profileID
select p;
another less efficient option is Contains:
var ccData = from p in db.ChannelContacts
where profiles.Contains(p.ProfileId)
select p;
Simply ask, if profile contains that ProfileId
var ccData = (from p in db.ChannelContacts
where profile.Any(prof => prof == p.ProfileId)
select p);
var query = from r in list where r.Id == "" DefaultIfEmpty(String.Empty)
does not work.
How do I have to write a linq query with query style and use the DefaultIfEmpty method?
Assuming your list contains the type Item you would want:
// define your default item
var defaultItem = new Item { ... };
var query = (from r in list where r.Id == "" select r).DefaultIfEmpty(defaultItem);
or in method syntax
var query = list.Where( r => r.Id == "" ).DefaultIfEmpty(defaultItem);
However if you're selecting a specific string property of Item then you may want something like
var query = (from r in list where r.Id == "" select r.StringProperty)
.DefaultIfEmpty(string.Empty);
DefaultIfEmpty is used usually with JOINS, (outer joins).
You may see: How to: Perform Left Outer Joins (C# Programming Guide)
For your case it apears you want to select empty string if the r.Id is null, you can you can do:
var query = from r in list
select new
{
ID = r.Id == null ? string.Empty : r.Id
};
I have this LINQ query:
var returnList = from TblItemEntity item in itemList
join TblClientEntity client in clientList
on item.ClientNo equals client.ClientNumber
join TblJobEntity job in jobList
on item.JobNo equals job.JobNo
where item.ClientNo == txtSearchBox.Text //Is this filter wrong?
orderby client.CompanyName
select new { FileId = item.FileId, CompanyName = client.CompanyName, LoanStatus = item.LoanStatus, JobNo = job.JobNo, JobFinancialYE = job.JobFinancialYE, VolumeNo = item.VolumeNo };
Why doesn't this return anything?
P/S : All of them are of string datatype.
Have you tried to remove parts of the join to figure out where the problem is and then add those removed parts back again one after one? Start with:
var returnList = from TblItemEntity item in itemList
where item.ClientNo == txtSearchBox.Text //Is this filter wrong?
select new { FileId = item.FileId };
Since you're doing inner joins there could be that one of the joins filters out all the items.
EDIT: When debugging don't expand the return type, the select new {FileId = item.FileId} is all you need to debug.
Still waiting on that sample data.
You say you're getting results filtering by other attributes so why should this be any different? Assuming the user-input txtSearchBox has a reasonable value, try printing the values out onto the debug console and see if you're getting reasonable results. Look at the output window. Try this version of your query:
Func<string,bool> equalsSearch = s =>
{
var res = s == txtSearchBox.Text;
Debug.WriteLine("\"{0}\" == \"{1}\" ({2})", s, txtSearchBox.Text, res);
return res;
};
var returnList = from TblItemEntity item in itemList
join TblClientEntity client in clientList
on item.ClientNo equals client.ClientNumber
join TblJobEntity job in jobList
on item.JobNo equals job.JobNo
//where item.ClientNo == txtSearchBox.Text //Is this filter wrong?
where equalsSearch(item.ClientNo) //use our debug filter
orderby client.CompanyName
select new { FileId = item.FileId, CompanyName = client.CompanyName, LoanStatus = item.LoanStatus, JobNo = job.JobNo, JobFinancialYE = job.JobFinancialYE, VolumeNo = item.VolumeNo };
Why doesn't this return anything?
There two possibilites:
1) The join is empty, that is, no items, clients and jobs have matching ID's.
2) The where clause is false for all records in the join.
To troubleshoot this you will have to remove the where clause and/or some of the joined tables to see what it takes to get any results.