OrderBy with Dynamic Linq - c#

I am trying to sort some data from entity before passing them to another function. Both tableName and columnName are selected dynamically. This is what I'm doing:
string tableName = cboSelectTable.Text.ToString();
var comboBoxColumn = from a in Context.RULES where
a.ISCOMBOBOXCOLUMN == "Y" select a.COLUMN;
foreach (var colName in comboBoxColumn)
{
var getTableName = entityModel.GetType()
.GetProperty(tableName)
.GetValue(entityModel, null);
var getData = ((IQueryable<object>)getTableName)
.Where(colName + "!=null")
.Select(colName)
.Distinct()
.OrderBy('"'+ colName +'"');
dgvCboColumn(getData, colName);
}
But this is not sorting the data. I also tried some other methods too, but couldn't figure it out. How can I resolve this?

I do not think that is the way, .OrderBy(...) works. Try ordering by an attribute:
SomeList.OrderBy(l => l.SomeAttribute);
I suspect ordering by a string results in each element being ordered by the same attribute, thus not ordering at all. In addition, I am not sure, if your where-clause works like that.
There is another relevant SO question already answered. You might want to have a look at it: click me!

You can simply place the Select after the OrderBy:
var getData = ((IQueryable<object>)getTableName)
.Where(colName + "!=null")
.OrderBy(colName)
.Select(colName)
.Distinct();
This will allow you to reference the column name. (doesn't seem to work for some reason).
Alternatively, you can reference the current instance:
var getData = ((IQueryable<object>)getTableName)
.Where(colName + "!=null")
.Select(colName)
.Distinct()
.OrderBy("it");

Related

Trying to get a list of a single field from all the documents in my Mongo database

I'm using the last driver. My documents are of the form
{
"ItemID": 292823,
....
}
First problem: I'm attempting to get a list of all the ItemIDs, and then sort them. However, my search is just pulling back all the _id, and none of the ItemIDs. What am I doing wrong?
var f = Builders<BsonDocument>.Filter.Empty;
var p = Builders<BsonDocument>.Projection.Include(x => x["ItemID"]);
var found= collection.Find(f).Project<BsonDocument>(p).ToList().ToArray();
When I attempt to query the output, I get the following.
found[0].ToJson()
"{ \"_id\" : ObjectId(\"56fc4bd9ea834d0e2c23a4f7\") }"
It's missing ItemID, and just has the mongo id.
Solution: I messed up the case. It's itemID, not ItemID. I'm still having trouble with the sorting.
Second problem: I tried changing the second line to have x["ItemID"].AsInt32, but then I got an InvalidOperationException with the error
Rewriting child expression from type 'System.Int32' to type
'MongoDB.Bson.BsonValue' is not allowed, because it would change the
meaning of the operation. If this is intentional, override
'VisitUnary' and change it to allow this rewrite.
I want them as ints so that I can add a sort to the query. My sort was the following:
var s = Builders<BsonDocument>.Sort.Ascending(x => x);
var found= collection.Find(f).Project<BsonDocument>(p).Sort(s).ToList().ToArray();
Would this be the correct way to sort it?
Found the solution.
//Get all documents
var f = Builders<BsonDocument>.Filter.Empty;
//Just pull itemID
var p = Builders<BsonDocument>.Projection.Include(x => x["itemID"]);
//Sort ascending by itemID
var s = Builders<BsonDocument>.Sort.Ascending("itemID");
//Apply the builders, and then use the Select method to pull up the itemID's as ints
var found = collection.Find(f)
.Project<BsonDocument>(p)
.Sort(s)
.ToList()
.Select(x=>x["itemID"].AsInt32)
.ToArray();

How to get the Columns from a WebMatrix Query?

The title is pretty self-explanitory, and it seems like it should be an easy task, but everything I've tried has not worked:
Here's my code, which works fine, but the table is variable, so I need to know the Columns it comes back with:
var data = db.Query("SELECT * FROM " + Table);
Here's a list of techniques I've tried:
data.GetType().GetProperties().ToList();
// prints 'Int32 Count' and 'System.Object Item [Int32]'
data.GetDynamicMemberNames()
// Error: '...IEnumerable<dynamic> does not have a definition for GetDynamicMemberNames'
// I also tried using System.Linq and System.Dynamic
I could also iterate through a loop, but there's got to be a more elegant way, right?
I'd like to end up with a List<String> of the Column Names.
List<String> cols = data.First().Columns;
It turns out the Columns Propery is an IList<string> type.
However, it is a property of an individual row of the data result (a row is a DynamicRecord data type), so it is unfortunately inaccessible from the result Object (data in my example). To access it, you need to get a single row, and .First() seems to be a pretty easy way to do that.
Here's my whole code in case anyone needs it:
WebMatrix.Data.Database db = new WebMatrix.Data.Database();
db.Open("ConnectionString");
var data = db.Query("SELECT * FROM " + Table);
List<String> cols = data.First().Columns;

C# Linq-SQL query result returning nothing

I'm fairly new to LINQ (and SQL at that). When trying to query my SQL Database in C# "Supervisors" (which contains only one column "Names" made of nvarchar(50) variables, none of which are Null), supvName ends up being an empty list. If I don't cast it as a List, supvName is of typeSystem.Data.EnumerableRowCollection<string> if that helps.
public addNewEmp()
{
InitializeComponent();
using (TestDataSet db = new TestDataSet())
{
var supvName = (from n in db.Supervisors
select n.Names).ToList();
foreach (string n in supvName)
{
supv_cbox.Items.Add(n);
}
}
}
Even when using a Where statement, that one result doesn't show up, so I'm sure it's something simple in my code that I just can't seem to figure out. I've already tried using AsEnumerable() which didn't change anything.
EDIT: I'm doing this in VS 2010 WPF. Also when I Preview Data in TestDataSet.xsd, it does return the all the data in the Database.
Solution: The problem was when I used a DataSet. When I used a DataContext instead it worked perfectly fine. Thanks to your DataSet or DataContext question lazyberezovsky or I never would have tried that.
Using the following works:
var supvName = db.Supervisors.Select(m => m.Names);
supv_cbox.ItemsSource = supvName;
Thanks Surjah Singh too.
When you are enumerating over DataTable with Linq to DataSet, you should call AsEnumerable() on datatable and use Field<T> extension to get column value:
var supvName = (from r in db.Supervisors.AsEnumerable()
select r.Field<string>("Names")).ToList();
BTW query variable r will be of DataRow type.
Your code can be simplified to:
var names = db.Supervisors.AsEnumerable().Select(r => r.Field<string>("Names"));
supv_cbox.DataSource = names.ToList();
//Var supvName = Supervisors.Select(m=>m.Names);
var supvName = from s in Supervisors.Tables[0].AsEnumerable()
select s.Field<string>("Names");

DataTable Find Item

im trying to do something like this
var names_en = dtTmp.AsEnumerable();
var names = names_en.Where(a => a["ID"] == "1");
string name = names["Name"].ToString();
My goal is to find the row where ID equalls 1 and keep the Name as string
I know I have ID collumn I know that I have a row where ID==1 I see it in the debugger.
but names lets that enumeration yields no results.
also is there a better way to do this?
Its better if you use DataRowExtension.Field method which is strongly typed. Also make sure you ID is of type string, otherwise you will get an exception. You may specify the type accordingly.
string name = dtTmp.AsEnumerable()
.FirstOrDefault(r => r.Field<string>("ID") == "1")
.Field<string>("Name");
var names = names_en.Where(a => a["ID"] == "1");
return the List of result you must get the first record

Select single column from dataset with LINQ

Just getting my head around all this LINQ stuff and it seems I'm stuck at the first hurdle.
I have a datatable as such:
OrderNo LetterGroup Filepath
----------- ----------- --------------------------------------------------
0 0 Letters/SampleImage.jpg
0 0 Letters/UKPC7_0.jpg
0 0 Letters/UKPC8_0.jpg
What I need is to get all of the filepaths from the Filepath column into a String array. I thought LINQ would be perfect for this (am I right?), but can't seem to construct the correct query.
Can anyone provide some code samples that would point me in the right direction? I have searched around - but don't seem to be getting anywhere.
There are extension methods which make working with data sets much easier:
using System.Data.Linq;
var filePaths =
from row in dataTable.AsEnumerable()
select row.Field<string>("Filepath");
var filePathsArray = filePaths.ToArray();
You can also use the method syntax to put it in one statement:
var filePaths = dataTable
.AsEnumerable()
.Select(row => row.Field<string>("Filepath"))
.ToArray();
string[] filePaths = (from DataRow row in yourDataTable.Rows
select row["Filepath"].ToString()).ToArray();
If you want to use LINQ all the way, set up your database and create a context object. Then you should be able to do something like this:
var filepaths = from order in _context.Orders
select order.Filepath;
This is assuming your table for the row is named Orders, which I guess by your first column name of order. If you wanted to return a set of the order numbers as well for using later to know where the file path came from you could do something like so:
var results = from order in _context.Orders
select new
{
order.OrderNo,
order.Filepath
}
This would give you a new anonymous type that contained both those values as properties.

Categories