Linq, VB - Anonymous type cannot be converted to anonymous type - vb.net

I'm a Linq noobie, maybe someone can point me in the right direction. What's wrong here? These anonymous types seem to have the same signatures.
'*** Get all of the new list items'
Dim dsNewFiles = From l1 In list1 _
Where Not (From l2 In list2 _
Select l2.id, l2.timestamp).Contains(New With {l1.id, l1.timestamp})
I wish there were some way to highlight in the above code, but I get the compile error:
Value of type '<anonymous type> (line n)' cannot be converted to '<anonymous type> (line n)'.
on the ".Contains(New With{l1.id, l1.timestamp})"
I assume it thinks the anonymous types are different in some way, but the id and timestamp columns are the same in either list. They are also in the same order. What else can be different between the two?
[Edit 7/10/2009 16:28 EST]
I tried the suggested code from user Meta-Knight (New With {Key l1.id, l1.timestamp}) and it fixed the compile error. However, when I ran the code with List1 and List2 as follows:
List1 List2
id timestamp id timestamp
-- ---------- -- ----------
01 2009-07-10 00:00:00 01 2009-07-10 00:00:00
The result was:
dsNewFiles
id timestamp
-- ----------
01 2009-07-10 00:00:00
It should have been an empty list.

Just change the last part of your code to:
New With {Key l1.id, Key l1.timestamp}
I tested the code and it works.
Edit:
I don't know why this doesn't work for you, I'll post the whole code just to be sure.
Dim dsNewFiles = From l1 In list1 _
Where Not (From l2 In list2 _
Select l2.ID, l2.TimeStamp).Contains(New With {Key l1.ID, Key l1.TimeStamp})
Another option is to simply do the following:
Dim dsNewFiles = list1.Except(list2)
For this to work, your class must override Equals and GetHashCode, and implement the IEquatable(Of T) interface. There's a very good example on MSDN (at the bottom).
If ID and Timespan don't represent equality in your class, you can use a custom IEqualityComparer(Of T) as a second argument.

When you generate anonymous types, they will be generated as separate types if they don't specify their properties with the same name and in the same exact order. So your example is the same as if I did this:
Class A
BeginClass
Begin ID as Int Begin ... End
Stuff as String Begin ... End
EndClass
Class B
BeginClass
Begin Stuff as String Begin ... End
ID as Int Begin ... End
EndClass
From a In someListofAs
Where Not (From b In someListofBs Select b).Contains(a)
That's complete air code, btw.
Also, in your example one part of your LINQ is an anonymous type and the other isn't. That might be your problem.
Try this:
From l1 In list1 _
Where Not (From l2 In list2 _
Select New With { ID = l2.id, Timestamp = l2.timestamp}).Contains(
New With { ID = l1.id, Timestamp = l1.timestamp})

Related

Is there a way to pass the name of a field to a setter function?

Here I have several functions that all just set a single field on a model record.
In a more dynamic language, I'd just have a single setter function and pass it the name of the field (as a string) and the value that I want to set on the model object.
Is there a way to pass the name of the field in Elm?
What's the Elm way of doing something like this?
type alias Patient =
{ id : String
, name : String
, dateOfBirth : String
, sex : String
... other fields
}
setPatientName : Patient -> String -> Patient
setPatientName patient value =
{ patient | name = value }
setPatientDateOfBirth : Patient -> String -> Patient
setPatientDateOfBirth patient value =
{ patient | dateOfBirth = value }
setPatientSex : Patient -> String -> Patient
setPatientSex patient value =
{ patient | sex = value }
... many others
-- idx is the index of the patient in the model (which is an array of patients)
-- UpdateCell is a variant of my Msg type, like this: UpdateCell Int (Patient -> String -> Patient) String
onInputHandler : Int -> (Patient -> String -> Patient) -> String -> Msg
onInputHandler idx setter inputText =
UpdateCell idx setter inputText
-- idx is the index of the patient in the model (which is an array of patients)
createTableRow : Int -> Patient -> Html Msg
createTableRow idx patient =
...
, input [ type_ "text", onInput (onInputHandler idx setPatientName), value patient.name ] []
, input [ type_ "text", onInput (onInputHandler idx setPatientDateOfBirth), value patient.dateOfBirth ] []
...
I'm currently using each of these functions as an event handler for input elements. So I need a function that I can use for handling the input event. Ideally, I'd define just a single function and use that single one for all the input elements and pass it the field I want to update on the patient record.
The short answer is "no". But this seems a bit like an XY problem. It's not clear what benefit you are trying to achieve since the full application of such a function would be longer than the equivalent record update expression:
setField "name" patient value
-- vs
{ patient | name = value }
and as a partially applied function is only slightly shorter than the equivalent anonymous function with shortened argument names:
setField "name"
-- vs
\r x -> { r | name = x }
Although the latter is significantly noisier with all the symbols.
There is also a short-hand function for getting a record field:
.name
-- vs
\r -> r.name
So there is some precedent for having a dedicated syntax for setter functions too, but unfortunately there is not. Likely because it would complicate the language, and the syntax in particular, for relatively little benefit. I'm therefore curious about what you're actually trying to accomplish.
Edit after question update:
Putting functions in the Msg is a very bad idea because it goes against the Elm Architecture. It makes the state transition opaque and won't work very well with the debugger. When something goes wrong you can still see the state before and after, but you'll have trouble understanding what happened, and why it happened, because that information is encoded in an opaque function which probably isn't the one it should be.
You'll also have trouble factoring your logic. If you need something to happen only when a certain field updates, you might have to put the logic in the view, or special-case that field by putting the logic for that in update while the rest is in view, for example. Either way, you're on the path to a messy code base.
You should generally use names for messages that describe what happened, not what to do, because that tends to lead to an imperative mindset. Instead of UpdateCell you could call it InputChanged, for example. Then instead of the function you should have an identifier for the field. Ideally a custom type, like InputChanged Name, but even a string will work, though it will be much easier to miss a typo.
So instead of setter functions for each field you'll just case match the message and set the field in the update function:
InputChanged Name value ->
{ patient | name = value }
-- vs
setPatientName : Patient -> String -> Patient
setPatientName patient value =
{ patient | name = value }
Then if you need to clear the sex when the name changes, for example (because reasons...), you can simply do:
InputChanged Name value ->
{ patient | name = value, sex = "" }
The Elm Architecture is good because it makes changes easy and safe, not because it's concise and free of boiler-plate. Good Elm code often has a lot of copy-and-paste, but that's not always bad.

Force FsCheck to generate NonEmptyString for discriminating union fields of type string

I'm trying to achieve the following behaviour with FsCheck: I'd like to create a generator that will generate a instance of MyUnion type, with every string field being non-null/empty.
type MyNestedUnion =
| X of string
| Y of int * string
type MyUnion =
| A of int * int * string * string
| B of MyNestedUnion
My 'real' type is much larger/deeper than the MyUnion, and FsCheck is able to generate a instance without any problem, but the string fields of the union cases are sometimes empty. (For example it might generate B (Y (123, "")))
Perhaps there's some obvious way of combining FsCheck's NonEmptyString and its support for generating arbitrary union types that I'm missing?
Any tips/pointers in the right direction greatly appreciated.
Thanks!
This goes against the grain of property based testing (in that you explicitly prevent valid test cases from being generated), but you could wire up the non-empty string generator to be used for all strings:
type Alt =
static member NonEmptyString () : Arbitrary<string> =
Arb.Default.NonEmptyString()
|> Arb.convert
(fun (nes : NonEmptyString) -> nes.Get)
NonEmptyString.NonEmptyString
Arb.register<Alt>()
let g = Arb.generate<MyUnion>
Gen.sample 1 10 g
Note that you'd need to re-register the default generator after the test since the mappings are global.
A more by-the-book solution would be to use the default derived generator and then filter values that contain invalid strings (i.e. use ==>), but you might find it not feasible for particularly deep nested types.

jOOQ - create value for field

I have a Field Field<T>. I want to create a named value for that field, to be able to use it in a query. The name of the value should be the name of the field.
select value as field from ...
Is the the correct way to do it?
public <T> Field<T> namedValue(Field<T> field, T value) {
return DSL.val(value, field).as(field);
}
Although it works, I was wondering if there is a shorter way to do this. I might be pedantic here :).
update
I am creating the following construction:
UPADTE table SET x = alias.x, y = alias.y
FROM (SELECT constant value for x, table2.y FROM table2 WHERE ...) AS alias.
Let's simplify this to (for the sake of this example, to focus on the constant selection):
SELECT
FROM (SELECT constant value for x) AS alias.
First, I started with:
Select s1 = context.select(DSL.val("TEST"));
Select s2 = context.select(s1.fields()).from(s1);
This resulted in an incorrect query:
select "alias_66794930"."TEST" from (select 'TEST') as "alias_66794930"
(I am not really sure if this is correct behavior from jOOQ.)
So, I added an alias:
Select s1 = context.select(DSL.val("TEST").as(X));
Select s2 = context.select(s1.fields()).from(s1);
This resulted in:
select "alias_76324565"."x" from (select 'TEST' as "x") as "alias_76324565"
This works fine. Then, I ran into problems when the constant vale was null:
Select s1 = context.select(DSL.val(null).as(X));
Select s2 = context.select(s1.fields()).from(s1);
This resulted in:
select "alias_85795854"."x" from (select cast(? as varchar) as "x") as "alias_85795854"
1400 [localhost-startStop-1] TRACE org.jooq.impl.DefaultBinding - Binding variable 1 : null (class java.lang.Object)
This makes sense, the field type is not known. So I added the field (with its type) as following:
Select s1 = context.select(DSL.val(null, X).as(X));
Select s2 = context.select(s1.fields()).from(s1);
Binding is now correct:
1678 [localhost-startStop-1] TRACE org.jooq.impl.DefaultBinding - Binding variable 1 : null (class java.lang.String)
All done!
I don't think you can get much shorter than what you already have. I mean, your SQL reads:
value as field
And your Java/jOOQ code reads:
DSL.val(value, field).as(field)
You could of course static import DSL.val or DSL.*:
import static org.jooq.impl.DSL.*;
And then shorten things to:
val(value, field).as(field)
And if you're very sure about value's type, you don't need to coerce it to that of field
val(value).as(field)
Now, you definitely can't go any shorter, and there's no more need for your namedValue() function...

LinqToSQL Union casting error when selecting multiple columns (Unable to cast DataQuery of... to IEnumerable of...)

I had a run-time error when the following code was executed: (vb.net)
dim q = (From x in db.T1
select x.F11, x.F12).Union( _
(From y in db.T2
select y.F21, y.F22)
F11 and F21 have the same type; F21 and F22 have the same type.
The runtime error stated "Unable to cast from DataQuery(of anonymous type(...) to iEnumerable (of anonymous type...
Union on anonymous types should work. Compiler is intelligent enough to treat two anonymous types are same. Double check your field types in database of tow tables they should be exactly same
You can try union on same table to see this
(From x in db.T1
select FIRST=x.F11, SECOND=x.F21).Union( _
(From y in db.T1
select FIRST=y.F11, SECOND=y.F21)
I now understand that using Anonymous type IS allowed in Union.
- You only need to make sure the field NAMEs and TYPEs are the same in the unioned queries, as in the example:
dim q = (From x in db.T1
Select FIRST = x.F11, LAST = x.F12).Union _
(From y in db.T2
Select FIRST = y.F21, LAST = y.F22)
and F11 and F21 are of the same type; F12, F22 are of the same type

Operator '=' is not defined for types 'Integer' and 'IQueryable(Of Integer)'

This is giving me a headache. I have this link query here that grabs an ID
Dim mclassID = From x In db.SchoolClasses Where x.VisitDateID = _visitdateID Select x.ClassID
And then later on I have this linq query
ViewData("Staff") = From t In db.Staffs Where t.ClassID = mclassID Select t
Any help would be much appreciated. I've tried quite a few things but to no avail. I've attempted casting, converting, Is operand, etc.
The problem is that myClassID is an anonymous IQueryable. You need to force it into another type (List is my favorite), and then pull it out of that type. So if you were to select it into a List(Of Integer) you could then extract the First() one since it would be the only. You could try something like this:
Dim myClassIDList As List(Of Integer) = New List(Of Integer)( _
From x In db.SchoolClasses Where x.VisitDateID = _visitdateID Select x.ClassID)
Dim myClassID as Integer = myClassIDList.First()
Just a guess, but would it help to wrap the right-side of the equation in parenthesis? I.e.:
ViewData("Staff") = (From t In db.Staffs Where t.ClassID = mclassID Select t)
Using the Select operator, you can have multiple results returned. If you are only expecting one result (i.e. you are selecting by a primary key), then you can use Single or SingleOrDefault (depending on whether there is guaranteed to be a result) to get just that one.
Dim mclassID = (From x In db.SchoolClasses _
Where x.VisitDateID = _visitdateID _
Select x.ClassID).SingleOrDefault()
You should change this
Dim mclassID = From x In db.SchoolClasses Where x.VisitDateID = _visitdateID Select x.ClassID
to select a single instance or the first instance, otherwise it does as its reporting, returning an IEnumerable, which causes your error later.
Or you could change your second statement to something like
ViewData("Staff") = From t In db.Staffs Where mclassID.Contains(t.ClassID) Select t
taking advantage of the mclassID as an IEnumerable of int.
You can see the errors in Output if you set appropriate options: -
Navigate VS2010 menus to Tools/Options/Projects and solutions/Build and Run/
Set MSBuild Project build output verbosity to "Detailed"
I had a similar error that wasn't showing in the Error list, but with this options setting I saw: -
error BC30452: Operator '=' is not defined for types 'System.Nullable(Of Integer)' and 'Integer'.
from this statement: -
If tqGDBChart.UserIsGroupAdmin(Userid, Groupid) = 0 Then 'User is not a group admin for this group
Easily fixed it with an intermediate variable.
Dim GroupAdminCount As Integer = tqGDBChart.UserIsGroupAdmin(Userid, Groupid)
If GroupAdminCount = 0 Then 'User is not a group admin for this group
have you tried:
ViewData("Staff") = From t In db.Staffs Where t.ClassID.equals(mclassID) Select t