I want to set the column names of an output from LINQ dynamically. Like so:
summary Rows.Field<Type>("Name")
I need to do this because I have to do the order by on three columns based on the a condition and each column have 2 different types like float, int and double
Does anyone have any suggestions on how this can be done?
LINQ to SQL deals with static types, though there are some tricks you can do. You can't change the type of the field on the fly, other than to use Convert.ToInt32, etc. to change the appropriate type to the value you need at the time you want to cast it.
Alternatively, you could try casting the value to each of the three types from the query:
from c in ctx
select new
{
IntVal = c.Value,
DoubleVal = Convert.ToDouble(c.Value),
.
.
}
This way, you'd have all three cast appropriately and can suck in the correct field. When working with the record, you can even use a wrapper around reflection to get something similarly to what you want. I don't know of Convert is LINQ supported, but you should be able to do something similarly.
HTH.
Related
I have a SQL view which takes two parameters. One of these parameters is a list of numbers in string form.
I can't for the life of me figure out if Geoserver can take this list and parse it.
The basic SQL query i've set up works as below
SELECT * FROM table WHERE id IN '%list%' AND layer = '%layer_name%'
When I put the default value for %list% as "1, 2 ,3" as an example, the call to viewparams might look like this
viewparams=layer_name:'layer_y';ids:1,2,3
Which fails. I've figured out that viewparams uses semicolons to distinguish between parameter types,
and commas as a way to distinguish between viewparams for different layers.
So I need a way of encapsulating my list of id values so that geoserver can parse them correctly.
Does anyone know how to do this?
I have a query that fetches books, I'm new to LINQ so I don't know the syntax:
var books = (from book in db.Books
join borrow in db.Borrows on book equals borrow.Book
select new BookDTO { Title = book.Title,
Borrows = book.Borrows.ToList() }).ToList(); // book.Borrows.ToList() <- use dto's instead
How can I select Book.Borrows as a list of objects (BorrowDTO's)? Is there something like Borrows = new List<BorrowDTO>(book.Borrows)
You can use .Select() to project the list into a different type. So instead of this:
Borrows = book.Borrows.ToList()
you would have something like this:
Borrows = book.Borrows.Select(b => new BorrowDTO { /* properties here */ }).ToList()
Note that, depending on your data source, there may be more efficient ways to approach selecting your data. If you're pulling directly from LINQ To Entities then you may run into problems trying to materialize a type within the query that isn't known to the DB, or any other operation that can't be translated into SQL. It's also not necessarily wise to toss in a bunch of .ToList() operations without a specific purpose.
But that's all theoretical at this point in the question. Based on the code shown and on LINQ syntax itself, you can select from a list just fine. (I'd even recomment using the extension method syntax more than the query syntax that you currently use. Personal preference of course, but I find it easier and more intuitive to build nested operations like this. Though you can just as well use the from ... select ... syntax after Borrows =, I would imagine.)
Just select book.Borrows instead of creating a new temporal object.
That query is going to return a IEnumerable of the Borrows type; and you'll be able to iterate through it and convert it into a List if you please
I have this here:
Dim query = FromTableRows.Select(Function(Row) Row.Item(_SqlSyntaxChecker.SelectedFields(0)))
Row is a normal DataRow, so I can get the field value of the rows like this: Row.Item(0), Row.Item(1), etc.
SelectedFields contains the field names of the FromTableRows.
Now, I would like to select all the fields in the SelectedFields list, while the number of the selected fields can vary.
Is this possible? How should I modify the code?
Thanks.
You can simply make use of the ItemArray property, if I understand your question correctly.
FromTableRows.Select(Function(Row) Row.ItemArray)
The ItemArray property is an object array that contains the elements found in the DataRow. You will, of course, lose any mapping via this method from columns to elements, but it sounds like that's what you want.
I'm having a problem joining two LINQ queries.
Currently, my (original) code looks like this
s.AnimalTypes.Sort((x, y) => string.Compare(x.Type, y.Type));
What I'm needing to do is change this based on a date, then select all data past that date, so I have
s.AnimalTypes.Select(t=>t.DateChanged > dateIn).ToList()
s.AnimalTypes.Sort((…
This doesn't look right as it's not sorting the data selected, rather sorting everything in s.AnimalTypes.
Is there a way to concatenate the two LINQ lines? I've tried
s.AnimalTypes.Select(t=>t.DateChanged > dateIn).ToList().Sort((…
but this gives me an error on the Sort section.
Is there a simple way to do this? I've looked around and Grouo and OrderBy keep cropping up, but I'm not sure these are what I need here.
Thanks
From your description, I believe you want something like:
var results = s.AnimalTypes.Where(t => t.DateChanged > dateIn).OrderBy(t => t.Type);
You can call ToList() to convert to a List<T> at the end if required.
There are a couple of fundamental concepts I believe you are missing here -
First, unlike List<T>.Sort, the LINQ extension methods don't change the original collections, but rather return a new IEnumerable<T> with the filtered or sorted results. This means you always need to assign something to the return value (hence my var results = above).
Second, Select performs a mapping operation - transforming the data from one form to another. For example, you could use it to extract out the DateChanged (Select(t => t.DateChanged)), but this would give you an enumeration of dates, not the original animal types. In order to filter or restrict the list with a predicate (criteria), you'd use Where instead.
Finally, you can use OrderBy to reorder the resulting enumerable.
You are using Select when you actually want to use Where.
Select is a projection from one a collection of one type into another type - you won't increase or reduce the number of items in a collection using Select, but you can instead select each object's name or some other property.
Where is what you would use to filter a collection based on a boolean predicate.
i need to insert a record with linq
i have a namevaluecollection with the data from a form post..
so started in the name=value&name2=value2 etc.. type format
thing is i need to inset all these values into the table, but of course the table fields are typed, and i need to type up the data before inserting it
i could of course explicitly do
linqtableobj.columnproperty = convert.toWhatever(value);
but i have many columns in the table, and the data coming back from the form, doesnt always contain all fields in the table
thought i could iterate over the linq objects columns, getting their datatype - to use to convert the appropriate value from the form data
fine all good, but then im still stuck with doing
linqtableobj.columnproterty = converted value
...if there is one for every column in the table
foreach(col in newlinqrowobj)
{
newlinqobj[col] = convert.changetype(namevaluecollection[col.name],col.datatype)
}
clearly i cant do that, but anything like that possible.. or
is it possible to loop around the columns for the new 'record' setting the values as i go.. and i guess grabbing the types at that point to do the conversion
stumped i am
thanks
nat
If you have some data type with a hundred different properties, and you want to copy those into a completely different data type with a hundred different properties, then somehow somewhere in your code you are going to have to define a hundred different "mapping" instructions. It doesn't matter what framework you are using, or whether the "mapping" instructions are lines of C# code, XML elements, lambda functions, proprietary "stuff", or whatever. There's no getting away from it.
Bearing that in mind, having one line of code per property looks to me like the fastest, simplest, most readable and maintainable solution.
If I understood your problem correctly, you could use reflection (or dynamic code generation if it is performance sensitive) to circumvent your typing problems
There is a preety good description of how to do something like this at codeproject.
Basically you get a PropertyInfo for the property you want to set (if it's not a property I think you would need dynamic code generation) and use it's setValue method (after calling the appropriate Convert.ChangeType of course). This will basicall circumvent the whole static typing, so there you are.