Create a string collection from CheckedListBox.CheckedItems using LINQ - linq

I have used the Entity framework to populate a checked list box. I want to get the names of the checked items as a string collection so that they can then be used as a filter for another LINQ query.
I populate the list box like this...
_eventTypesCheckedList.DataSource = this._dataContext.tblEventTypes.OrderBy(ev => ev.EventTypeName);
_eventTypesCheckedList.DisplayMember = "EventTypeName";
This is how I'm failing to get the string collection...
var types = from eType in ((_eventTypesCheckedList.CheckedItems) as IEnumerable< tblEventType > )
select new string( eType.EventTypeName.ToCharArray() );
Any help would be great.

Cast your CheckItems collection using .Cast<Type>() extension method:
_eventTypesCheckedList.CheckedItems.Cast<tblEventType>()

Related

Get All Entities From EntityCollection Where Values Matches X

I would like to get all matched Entities from an EntityCollection by a value, but my current statement only allow return of Entity, and not EntityCollection.
//only allow return 1 entity
var matchedRecords = allRecords.Entities.Where
(x => x.GetAttributeValue<EntityReference>
("ccc_batchId").Id == batchId);
May I know how can I tweak the above query?
EntityCollection is just a construct to store more than one Entity.
I know it's not ideal but you can always convert the allRecords.Entities inside a List of Entity and do your LINQ query against it.
Your code is probably returning an IEnumerable of Entity and not a single Entity (for example in the end of your query you can put a .ToList() to get a List of Entity.
Building on what Guido said, it is also possible to create a new EntityCollection with the results:
var matchedRecords = allRecords.Entities.Where(x => x.GetAttributeValue<EntityReference>("ccc_batchId").Id == batchId).ToList();
var matchedCollection = new EntityCollection(matchedRecords);

Dynamic Linq on DataTable error: no Field or Property in DataRow, c#

I have some errors using Linq on DataTable and I couldn't figure it out how to solve it. I have to admit that i am pretty new to Linq and I searched the forum and Internet and couldn't figure it out. hope you can help.
I have a DataTable called campaign with three columns: ID (int), Product (string), Channel (string). The DataTable is already filled with data. I am trying to select a subset of the campaign records which satisfied the conditions selected by the end user. For example, the user want to list only if the Product is either 'EWH' or 'HEC'. The selection criteria is dynaically determined by the end user.
I have the following C# code:
private void btnClick()
{
IEnumerable<DataRow> query =
from zz in campaign.AsEnumerable()
orderby zz.Field<string>("ID")
select zz;
string whereClause = "zz.Field<string>(\"Product\") in ('EWH','HEC')";
query = query.Where(whereClause);
DataTable sublist = query.CopyToDataTable<DataRow>();
}
But it gives me an error on line: query = query.Where(whereClause), saying
No property or field 'zz' exists in type 'DataRow'".
If I changed to:
string whereClause = "Product in ('EWH','HEC')"; it will say:
No property or field 'Product' exists in type 'DataRow'
Can anyone help me on how to solve this problem? I feel it could be a pretty simple syntax change, but I just don't know at this time.
First, this line has an error
orderby zz.Field<string>("ID")
because as you said, your ID column is of type int.
Second, you need to learn LINQ query syntax. Forget about strings, the same way you used from, orderby, select in the query, you can also use where and many other operators. Also you'll need to learn the equivalent LINQ constructs for SQL-ish things, like for instance IN (...) is mapped to Enumerable.Contains etc.
With all that being said, here is your query
var productFilter = new[] { "EWH", "HEC" };
var query =
from zz in campaign.AsEnumerable()
where productFilter.Contains(zz.Field<string>("Product"))
orderby zz.Field<int>("ID")
select zz;
Update As per your comment, if you want to make this dynamic, then you need to switch to lambda syntax. Multiple and criteria can be composed by chaining multiple Where clauses like this
List<string> productFilter = ...; // coming from outside
List<string> channelFilter = ...; // coming from outside
var query = campaign.AsEnumerable();
// Apply filters if needed
if (productFilter != null && productFilter.Count > 0)
query = query.Where(zz => productFilter.Contains(zz.Field<string>("Product")));
if (channelFilter != null && channelFilter.Count > 0)
query = query.Where(zz => channelFilter.Contains(zz.Field<string>("Channel")));
// Once finished with filtering, do the ordering
query = query.OrderBy(zz => zz.Field<int>("ID"));

LINQ Select from dynamic tableName string

I want to get list of records from an entity model (I'm using EF version 5) with a particular accountID. I'm being supplied with the tableName string (this has to be dynamic) and the accountID. I'm trying the following 2 methods but none of them is working (giving me errors on the IQueryable object 'table':
PropertyInfo info = _db.GetType().GetProperty(tableName);
IQueryable table = info.GetValue(_db, null) as IQueryable;
var query = table.Where(t => t.AccountID == accID)
.Select(t => t);
List <object> recList = ( from records in table
where records.AccountID == accID
select records).ToList<object>();
The var query = table.Where(....).Select(...) is the correct move as it allows reflection for the query builder at runtime. However, t.AccountID is an error because of the type of t remains unknown.
I've previously used a similar approach in LINQ to SQL, using System.Linq.Expressions.Expression, e.g.:
// NOT TESTED
var table=context.GetTable(dynamicTableName);
var theT=table.Experssion; // actually, I forget. DynamicExpression or MemberBinding? or
var theField=Expression.Field(theT, "AccountID"); // or dynamic name
var query=table.Where(Expression.Equal(theField, accID);
var recList=query.ToList<object>();
If your object has a common interface there is a simpler syntax:
IQueryable<MyInterface> table = context.GetTable("table") as IQueryable<MyInterface>;
var recList=from r in table
where table.AccountID == ac // if your AccountID is on MyInterface
select table;
If you only have a few tables to support, you could do this as well:
IQueryable<MyInterface> table;
if("table1"==tableName)
table=_db.table1
elseif("table2"==tableName)
table=_db.table2
elseif("table3"==tableName)
table=_db.table3
else
throw exception
I built a DynamicRepository for a project I am working on. It uses generic methods exposed through EF along with dynamic linq. It might be helpful to look at that source code here:
https://dynamicmvc.codeplex.com/SourceControl/latest#DynamicMVC/DynamicMVC/Data/DynamicRepository.cs
You can query the entity framework metadata workspace to get the type for a given table name. This link might help:
Get Tables and Relationships

IQueryable type to an Array

I have a dynamic Linq query like this. I need to convert the result set into an array. But I am not able to convert the IQueryable type to an Array. Any suggestion?
my code:-
var query = Data.AsEnumerable()
.AsQueryable()
.Select("new(it[\"Country\"] as Country)", "it")
.Take(10);
foreach (string str in query) // **getting error Unable to cast object of type 'DynamicClass1' to type 'System.String**
{
}
I fixed it using like this :- foreach(var str in query) .
But I have another issue now. I have added where condition to the query. Now i am getting error "No property or field 'Country' exists in type 'DataRow'".
following is my query
var query= Data.AsEnumerable().AsQueryable().Where("Country = #0", "London").Select("new (Country as Country)");
When you use Dynamic LINQ all extensions returns collection with dynamic elements, so you need change your code for example like this
foreach (dynamic str in query)
{
....
}
also for your case str is object with field Country
UPDATE
for question from comment
if Data is DataTable when you call AsEnumerable or AsQueryable you work with collection of DataRow, so when you want filter it by column value you need use syntax for DataRow like this
Data.AsQueryable().Where("it[\"Country\"] = #0", "London")
or you can do select first like that
var query= Data.AsQueryable()
.Select("new (it[\"Country\"] as Country)")
.Where("Country = #0", "London")
UPDATE2
until you don't specify type for field it can be Object so you need change Select clause like this
....
.Select("new(Convert.ToString(it[\"Country\"]) as Country)")
....
in this case when you call Where after Select field Country will is String, so String have Contains method

Convert IQueryable to List<T> type

I just performed a query with LINQ from the DAL and got a collection of a record with imbedded ILIST objects like the following
string name
date startDate
date endDate
ILIST<MyType> ImbeddedList (this contains more columns like recordID, sentDate, dueDate)
I need to return a LIST<T> back to the grid to be bounded.
I am having some problems with writing the LINQ statement to filter out the IQueryable collection object.
In my statement below:
IQueryable<All_DATA> cases = dalObject.GetData();
var mylist = cases.Select(s => {s.name, s.startDate, s.endDate,s.ImbeddedList????}).ToList();
When I get to the ImbeddedList, which is returned from the dalObject, the intellsense does not show the fields in the ImbeddedList. How can I correctly write the LINQ statement to filter for more fields in the ImbeddedList object?
As far I understand what you can do is
For fetching complete list from ImbeddedList
var mylist = cases.Select(s => {s.name, s.startDate, s.endDate, s.ImbeddedList}).ToList();
And for fetching individual field from ImbeddedList
var mylist = cases.SelectMany(s => s.ImbeddedList)
.Select(IItem => { IItem.Field1, IItem.Field2 }).ToList();
For more information please refer:
The Linq SelectMany Operator
LINQ - Get all items in a List within a List?
Using LINQ, select list of objects inside another list of objects
Use Google Search: "linq select list within list"

Resources