I am populating states DDL using the country DDL
public static IEnumerable bindcountry()
{
var countries = from c in getdata().Descendants(("country"))
orderby (string)c.Element("name")
select (string)c.Element("name");
return countries;
}
public List<string> GetStatesByCountry(string CountryName)
{
var query = from user in getdata().Descendants("country")
where user.Element("name").Value == CountryName
from t in user.Descendants("text")
select t.Value;
return query.ToList();
}
foreach (var VARIABLE in ProfileMasterDAL.bindcountry())
{
if (VARIABLE.ToString().Contains(DropDownList1.SelectedItem.Text))
{
var query = from row in ProfileMasterDAL.bindcountry()
where row.(ProfileMasterDAL.GetStatesByCountrys(DropDownList1.SelectedItem.Text))
select row;
DropDownList2.DataSource = query;
DropDownList2.DataBind();
}
}
The problem is I am unable to define WHERE clause and equals here I am getting an error:
Could not find an implementation of the query pattern for source type
'System.Collections.IEnumerable'. 'Where' not found. Consider
explicitly specifying the type of the range variable 'row'.
You say that you are trying to populate a DropDownList with the names of the States for a given Country and it looks like that logic is in your foreach loop. It also looks like your foreach loop is doing a lot of unnecessary work.
It's iterating through all the Country names when it really only needs to find one of those country names. It also then iterates again through the country names looking for the states.
You should be able to throw out that entire foreach loop and instead use this:
var query = ProfileMasterDAL.GetStatesByCountry(DropDownList1.SelectedItem.Text);
DropDownList2.DataSource = query;
DropDownList2.DataBind();
Your GetStatesByCountry method returns just the states that belong to the passed in Country name, so you should just be able to call that, get the names of just those States, and then assign them to your DropDownList.
Try changing:
public static IEnumerable bindcountry()
{
var countries = from c in getdata().Descendants(("country")) orderby (string)c.Element("name") select (string)c.Element("name");
return countries ;
}
to
public static IList<string> bindcountry()
{
var countries = from c in getdata().Descendants(("country")) orderby (string)c.Element("name") select (string)c.Element("name");
return countries.ToList() ;
}
Related
I am a little weak in LINQ to SQL so will try to explain my problem.
I have a method as follows (simplified to explain it better):
public static List<ic_ProductData> GetCompleteSimilarProductsWithApplyButton(InfoChoiceAdminDataContext db)
{
var products = (from
p in db.ic_ProductDatas
join proddef in db.ic_ProductDefs on p.ProductDefId equals proddef.ProductDefId
select p
).ToList();
return products;
}
ic_ProductData and ic_ProductDefs are tables in my database
The ic_ProductData class contains a manually created property as:
public ic_ProductDef RelatedProductDef { get; set; }
I want to modify the above LINQ to SQL query so that I can populate this property.
Please note I do not want another call to the database.
Also there are a lot of properties in ic_ProductData so I want to avoid mapping each and every property
Something to the effect of the following (obviously the below is wrong):
public static List<ic_ProductData> GetCompleteSimilarProductsWithApplyButton(InfoChoiceAdminDataContext db)
{
var products = (from
p in db.ic_ProductDatas
join proddef in db.ic_ProductDefs on p.ProductDefId equals proddef.ProductDefId
//trying to change here
select new ic_ProductData
{
//do something with p here so that all the properties of new object gets filled
// avoid mapping of properties here
RelatedProductDef = proddef
}
).ToList();
return products;
}
With my limited knowledge I am stuck here.
Please help!
Thanks in advance!
You can do something like this:
var query = (from p in db.ic_ProductDatas
join proddef in db.ic_ProductDefs on p.ProductDefId equals proddef.ProductDefId
select new
{
ProductData = p,
Def = proddef
}).ToList();
List<ic_ProductData> products = new List<ic_ProductData>();
foreach( var product in query)
{
product.ProductData.RelatedProductDef = product.Def;
products.Add(product);
}
Basicly, you first need to do the one query to the database, this returns an anonymous type containing both your product and its Def.
Finally, you loop (in memory, no db-calls!) over these, creating your final objects with their RelatedProductDef properties populated.
I have a table in my LINQ to SQL portion of my project.
I'm just trying to perform a simple query like so:
public static string GetMLBID(int fk_players_id)
{
using (MLBDataClassesDataContext context = new MLBDataClassesDataContext())
{
var query = from a in context.players
where a.fk_player_type_id == fk_players_id
select a.mlb_com_id;
foreach (var b in query)
{
Console.WriteLine(b.); //<-- I don't get the properties listed in the "players" table that i linked in the imgur link.
}
}
}
From all the examples in google.. where i have "b.", the properties from the table i have should be popping up.. but that's not listed. i only get simple LINQ operators and methods.
I feel like i'm missing something really simple.. any help?
You are only selecting the id mlb_com_id
select a.mlb_com_id;
Change the select clause to
select a;
This allows you to access all the public members of a on the result set.
EDIT by Pellared. (The point of Pellared's addition is that the extension method syntax does not require a Select-clause and would therefore not have lead to the error):
You can also change the query using lamba expressions (which a lot of people prefer)
public static string GetMLBID(int fk_players_id)
{
using (MLBDataClassesDataContext context = new MLBDataClassesDataContext())
{
var query = context.players
.Where(a => a.fk_player_type_id == fk_players_id);
foreach (var b in query)
{
Console.WriteLine(b.mlb_com_id);
}
}
}
You need to get your elements as a list and you should be able to access the properties then.
public static string GetMLBID(int fk_players_id) {
using (MLBDataClassesDataContext context = new MLBDataClassesDataContext())
{
var query = (from a in context.players
where a.fk_player_type_id == fk_players_id
select a).ToList();
foreach (var b in query)
{
Console.WriteLine(b.first_name);
}
}
}
I have Two classes Named OfflineOrderLineItem.cs and OnlineOrderLineItem.cs both have diff Order table named offline and Online
In that i want to Combine the two tables data to search and Display the Fields from both tables
How to do that using linq in mvc4 ??? any idea.....
public virtual IPagedList<OnlineOrderLineItem> SearchOrderLineItems(string PoNumber)
{
var query1 = (from ol in _offlineOrderLineItemRepository.Table
select new
{
ol.Name
}).ToList();
var query2 = (from opv in _onlineOrderLineItemRepository.Table
select new
{
opv.Name
}).ToList();
var finalquery = query1.Union(query2);
if (!String.IsNullOrWhiteSpace(Name))
finalquery = finalquery.Where(c => c.Name == Name);
var orderlineitems = finalquery.ToList(); //its not working it throw a error
return new PagedList<OnlineOrderLineItem>(orderlineitems);//error
}
Error
cannot convert from 'System.Collections.Generic.List<AnonymousType#1>'
to 'System.Linq.IQueryable<Nop.Core.Domain.Management.OnlineOrderLineItem>'
to 'System.Linq.IQueryable<Nop.Core.Domain.Management.OnlineOrderLineItem>'
query1 and query2 are lists of an anonymous type with a single property of type string. (I assmume the ol.Name and opv.Name are strings.) Hence finalQuery and orderlineitems are collections of this anonymous as well. By specifying PagedList<T> you require that the collection passed into the constructor is an enumeration of type T. T is OnlineOrderLineItem, but the enumeration passed into the constructor is the anonymous type which is a different type. Result: compiler error.
To solve the problem I suggest that you define a named helper type that you can use to union the two different types OfflineOrderLineItem and OnlineOrderLineItem:
public class OrderLineItemViewModel
{
public int Id { get; set; }
public string PoNumber { get; set; }
public string Name { get; set; }
// maybe more common properties of `OfflineOrderLineItem`
// and `OnlineOrderLineItem`
}
Then your SearchOrderLineItems method should return a paged list of that helper type:
public virtual IPagedList<OrderLineItemViewModel> SearchOrderLineItems(
string PoNumber)
{
var query1 = from ol in _offlineOrderLineItemRepository.Table
select new OrderLineItemViewModel
{
Id = ol.Id,
PoNumber = ol.PoNumber,
Name = ol.Name,
// maybe more properties
};
// don't use ToList here, so that the later Union and filter
// can be executed in the database
var query2 = from opv in _onlineOrderLineItemRepository.Table
select new OrderLineItemViewModel
{
Id = opv.Id,
PoNumber = opv.PoNumber,
Name = opv.Name,
// maybe more properties
};
// don't use ToList here, so that the later Union and filter
// can be executed in the database
var finalquery = query1.Union(query2);
// again no ToList here
if (!string.IsNullOrWhiteSpace(PoNumber))
finalquery = finalquery.Where(c => c.PoNumber == PoNumber);
var orderlineitems = finalquery.ToList(); // DB query runs here
return new PagedList<OrderLineItemViewModel>(orderlineitems);
}
It is important to use ToList only at the very end of the query. Otherwise you would load the whole tables of all OnlineOrderLineItems and all OfflineOrderLineItems into memory and then filter out the items with the given PoNumber in memory which would be a big overhead and performance desaster.
Instead of
var orderlineitems = finalquery.ToList();
Try
var orderlineitems = finalquery.AsQueryable();
From https://github.com/TroyGoode/PagedList/blob/master/src/PagedList/PagedList.cs, PagedList takes a IQueryable<T>
Queryable.AsQueryable<TElement> Method
I have a List of the following object :
public class Item
{
public DateTime DliveryDate { get; set; }
public String Order { get; set; }
}
How can i group this List<Item> by Date using LINQ?
I used the following query but didn't got excepted result in a group by dates Got a List object with a junk date of 0001/1/1
var r = from i in Items
group i by i.DliveryDate into s
select s;
This should return what you need:
var listdategroup = from x in psrAlertLogItems.AsEnumerable<Item>()
group x by x.DliveryDate.Date into s
select s;
Maybe your ChangeDateTime contains hour/time information , you should do
var listdategroup = from i in psrAlertLogItems
group i by i.DliveryDate.Date into s select s;
to get only the day component of your datetime
May be this can help u..
var sorted_lists = from sort in lists
group sort by sort.DateInfo into sorted
select sorted;
I'm getting the correct result..
have you tried it using the extension method
var itemsGruopedByDate = Items.GroupBy(item => item.DliveryDate ).ToList();
Just an alternative.
I hope its of any use.
Cheers.
I have a datatable which contains a load of dates. I wanted to group these by date and give each row a count.
I have managed to do this by dong the following:
IEnumerable query = from row in stats.AsEnumerable()
group row by row.Field<string>("date") into grp
select new { Date = grp.Key, Count = grp.Count(t => t["date"] != null) };
(where "stats" is the datatable)
I can see from debugging that this brings back the values all grouped as I need, but now I need to loop them and get each date and count.
My problem is I don't know how to retrieve the values!
I have a foreach loop
foreach (var rw in query)
{
string date = rw.Date; // <---- this is my problem?
}
I don't know what type my Ienumerable is to be able to reference the values in it!
So my question is how can I retrieve each date and count for each row by doing similar to the above?
I hope this makes sense!
This link on my blog should help you
http://www.matlus.com/linq-group-by-finding-duplicates/
Essentially your type is an anonymous type so you can't reference it as a type but you can access the properties like you're trying to do.
I think I see your issue. If you're trying to return it from a method, you should define a type and reuturn it like shown below:
public IEnumerable<MyType> GetQuery()
{
var query = from row in stats.AsEnumerable()
group row by row.Field<string>("date") into grp
select new { Date = grp.Key, Count = grp.Count(t => t["date"] != null) };
foreach (var rw in query)
{
yield return new MyType(rw.Date, rw.Count);
}
}
declare your "query" variable using "var" as shown above.
I guess you don't have access to the properties of the anonymous class because you're using IEnumerable query = .... Try var query = ... instead.
Going by your comment "I am returning the query from a function", which I take to mean that you want to do the query in a method, return the data to the caller, and then iterate the data in the caller, I suggest you return a Dictionary<DateTime, int>, like this:
static Dictionary<DateTime, int> GetSummarisedData()
{
var results = (
from row in stats.AsEnumerable()
group row by row.Field<string>("date") into grp
select new { Date = grp.Key, Count = grp.Count(t => t["date"] != null) })
.ToDictionary(val => val.Date, val => val.Count);
return results;
}
then in the caller you can just
foreach (var kvp in GetSummarisedData())
{
// Now kvp.Key is the date
// and kvp.Value is the count
}