Unable to retrieve Dictionary value when used in LINQ - linq

I am trying to update a 'Name' DataColumn based on a 'ID' DataColumn in a DataTable.
The 'ID'-'Name' pairs are stored in a Dictionary, which is created using a DataTable extension method as follows:
public static Dictionary<object, object> ToDictionary(this DataTable dataTable, string keyColumn, string valueColumn)
{
Dictionary<object, object> resultDict = new Dictionary<object, object>();
if (dataTable.Columns.Contains(keyColumn) && dataTable.Columns.Contains(valueColumn))
{
foreach (DataRow dr in dataTable.Rows)
if (resultDict.ContainsKey(dr[keyColumn]) == false)
resultDict.Add(dr[keyColumn], dr[valueColumn]);
}
return resultDict;
}
I am using the following LINQ syntax to update the DataColumn:
misUserDetailsDT.AsEnumerable().ToList().ForEach(row => row.SetField("DepartmentName", deptDict[row["DepartmentID"]].ToString()));
Here 'misUserDetailsDT' is the DataTable containing a filled column 'DepartmentID' and an empty column 'DepartmentName'-which I am trying to update.
I have a seperate method which generates the Dictionary as follows:
var deptDict = departmentDT.ToDictionary("DeptID", "DeptName");
where 'departmentDT' is a DataTable containing columns 'DeptID' and 'DeptName'.
Now when I execute the Linq code it give a 'KeyNotFoundException'. I have thoroughly checked that the 'departmentDT' table as well as 'deptDict' have all the keys(departmentIDs) from the 'misUserDetailsDT' table. Actually the 'departmentDT' itself has been generated from all the distinct IDs of 'misUserDetailsDT' table.
I think there is some issue with figuring out the appropriate type of the Dictionary keys. I even tried casting it to Int16, but it didn't work out.
Please help me figure out a solution.

I have figured out the problem. The code works when dictionary values are casted to Int32. Thanks to #TimSchmelter for giving a very useful info. I will be changing the code to make use of foreach loop instead.

Related

Columns names from entity using LINQ

I was able to get the columns names by using this:
var props = typeof(FMCSA_NPR).GetProperties();
But it is also giving me the names of other tables which have a foreign relation with the specified table.
Is there a way by which I can only get the column names? What do we call column names when referring table as entity in Entity Model?
You can list the non-navigation properties of entities by accessing the conceptual model (CSpace):
var oc = ((IObjectContextAdapter)db).ObjectContext;
var cs = oc.MetadataWorkspace.GetEntityContainer(oc.DefaultContainerName,
DataSpace.CSpace);
foreach (var entitySet in cs.EntitySets)
{
var props = string.Join(",", entitySet.ElementType.Properties);
Trace.WriteLine(string.Format("{0}: {1}", entitySet.Name, props));
}
(Where db is your DbContext object).

MVC 3 controller GroupBy View error

Im creating an MVC 3 view from a controller. My model "MyList", contains a large number of records. When I create my model using the following linq statement:
var model = _db.MyList.GroupBy(r => r.myKey);
I'm getting the error: "The model item passed into the dictionary is of type 'System.Collections.GenericlList' 1... but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable' ...
In the view I have the following code in the first line:
#model IEnumerable<MyApp.Models.MyList>
I tried returning
return View(model.ToList());
from the controller, but no joy. What am I missing?
model.ToList() will return a List<T> where T is MyList. Your model type is straight MyList. If the var declaration you have above already returns MyList, just do return View(model).
This one was dogging me all morning. I found the answer to my question in the following post:
Linq Distinct() by name for populate a dropdown list with name and value
I basically return the following:
public static IEnumberable<MyModel> FindTheKeys(this IQueryable<MyModel> myList)
{
return myList.OrderBy(r => r.AreaKey);
}
and then performed the select as indicated in the above post.
var model = _db.MyModel.FindTheKeys().GroupBy(r => r.AreaKey).Select(g => g.First());
GroupBy returns a collection of IGrouping<TKey, TSource>, not MyList (which is strange anyways, you wouldn't have a list of a list.
It doesn't even make much sense to convert a GroupBy into a list anyways. Did you actuall mean OrderBy?

Get rid of duplicate entries in autocomplete

I am having difficulty getting rid of duplicate entries which are showing up in autocomplete.
The autocomplete is generated dynamically from a database.
This is the code which is being used for the autocomplete in the control:
public ActionResult AutoCompletefootball()
{
var db = new footEntities();
string selection = this.Request.Params["term"].ToString();
return Json(db.football.Where(a => a.player.Name.StartsWith(selection)).Select(Adds => a.Player.Name), JsonRequestBehavior.AllowGet);
}
All advice welcome
In your return statement (where you use LINQ), add DISTINCT clause.
.Distinct() will eliminate duplicates, but consider that duplicates are appearing because there are many players with the same name, so they are not really duplicate people

Order By property from dynamic linq

I am using dynamic linq to make a generic class for processing a generic JqGrid from MVC all works fine (searching, pagination etc) except for sorting on code properties. Sorting works fine when I am hitting the DB to sort the data, but as soon as it is a property I have made the sorting does not work eg
public partial class tblStockOrder
{
public string approved
{
get
{
return approved_id == null ? "" : "Approved";
}
}
}
I am running the following Dynamic Linq
items = items
.OrderBy(string.Format("{0} {1}", sidx, sord))
.Skip(pageIndex * pageSize)
.Take(pageSize);
Where sidx etc are strings passed in by jquery.
So basically what is the best solution for handling a case where some properties will be from the db while others will be code properties (not sure of the correct naming). I can handle all this in code using reflection but would obviously like the DB to handle as much of the searching / sorting as possible without pulling in thousands of records and sorting through them in code using reflection.
Computed class will of course not work, as you're trying to create record which is part in memory, part in database.
You can, however, compute the same on database by specifying the function in linq query, example:
items = items
.OrderBy(x=> x.approved_id != null )
.Skip(pageIndex * pageSize)
.Take(pageSize);

ADO.NET DataRow - check for column existence

How do I check for the existence of a column in a datarow?
I'm building datatables to organize some data that I've already pulled back from the database. Depending on the type of data in each row, I need to create a datatable with different columns. Then, later on, I want to check and see if the datatable I am looking at has a certain column.
I know I can catch the exception and handle it that way, but I'm curious if there is a property or method on the datarow object that will do this for me?
Here's how I can do it by catching the exception:
public static String CheckEmptyDataRowItem(DataRow row, String rowName, String nullValue)
{
try
{
return row[rowName].ToString();
}
catch (System.ArgumentException)
{
return nullValue;
}
}
You can simply check like this:
return row.Table.Columns.Contains(columnName);
DataTables have that schema info, so check if the Row's Table's Columns collection contains the field.

Resources