How to orderby conditionally using lambda and non lambda linq? |
As you need to keep the order of the elements with service.IsDefault ==
null, an easy solution is to split your dataset into two parts (first
service.IsDefault == null, second: service.IsDefault != null) sort the
second part, then, concat:
var transportationModes =
LogisticsService.GetTransportationModes<CarrierTransportationMode>(x
=>
x.CarrierId == carrierRoleId &&
x.ParentTransportationModeId != null
&&
!(x is LoadCarrierMode) &&
(x.ParentTransportationMode.TransportationModeStatus != null) &&
x.ParentTransportationMode.TransportationModeStatus.Value !=
TransportationModeStatus.Inactive)
var servi
|
How to perform an OrderBy from two different columns at the same time, not using ThenBy |
How about you do all of the EF LINQ to Entities work and then sort the
resulting list by whatever remaining logic you need, like this:
list.Sort(item => item.PropertyToSortBy);
And you can call it multiple times to sort by one property, then another,
etc.
Note: The class T in your List<T> must implement IComparable or
IComparable<T> for the simple syntax above to work.
|
Argument type 'lambda expression' is not assignable to parameter type 'System.Action' |
I doubt this has anything to do with mvvmcross or mvvm
A quick search for this error message suggests this is more likely to be
down to tooling - especially r# - eg see hits like:
http://devnet.jetbrains.com/thread/292248
http://caliburn.codeplex.com/discussions/212685
http://youtrack.jetbrains.com/issue/RSRP-178647?projectKey=RSRP
If you are running any extensions like r# and you remove or disable them,
then this may remove the warning.
If disabling them helps, then I would recommend asking the extension
vendor(s) for support.
If disabling them does not help, then I would recommend investigating the
differences between the two projects where the problem does/doesn't occur -
that will hopefully yield the answer.
|
Webgrid: Cannot convert lambda expression to type 'object' because it is not a delegate type |
You can't use embedded razor strings within the lambda expression, as
@Alessandro D'Andra suggests you have to use x => "<img src='" +
someString + "'></img>"; instead.
You might also have to wrap it all in an MvcHtmlString to prevent Razor
from escaping the string once it is used by the formatter, but I don't know
exactly how the formatter works - you have to try it.
I made a small test file to find out exactly what the Razor compiler would
do with your code. This is the razor file:
@{
string someString = "somestring";
Func<object, object> a = x => "<text><img src='" +
someString + "'></img></text>";
Func<object, object> b = x => @<text><img
src="@someString"></img></text>);
}
The ASP.NET
|
WPF: Cannot convert lambda expression to type 'string' because it is not a delegate type |
Your NotifyPropertyChanged expects a string, and you're passing it a
delegate. Try:
public string SelectedTransactionName
{
set
{
if (_selectedTransactionWsName == value) return;
this._selectedTransactionWsName = value;
// InitializaMessageElement(value.WsMethodName, transactionTypes);
InitializaMessageElement();
this.NotifyPropertyChanged("SelectedTransactionName");
this.NotifyPropertyChanged("IsTransactionNameSelected");
}
get
{
return this._selectedTransactionWsName;
}
}
|
linq query issues with date type data |
It looks like you have an DateTime that hasn't been set. The default value
of a DateTime is "01/01/0001 00:00:00".
// outputs the value of an empty DateTime: "01/01/0001 00:00:00"
Console.WriteLine(default(DateTime));
Are you sure that the dateofjoin is assigned? I don't see it in you code.
|
LINQ throwing TypeAs expression with input of type 1 and check of type 2 is not supported |
Unfortunately, you're going to have to do this dynamically. Generics
(combined with Entity Framework's apparent fear of typecasting) won't allow
you to write the code you want in a static manner. So try this instead:
using System.Linq.Expressions;
public static Expression<Func<TEntity, bool>>
DefaultFilter<TEntity>()
where TEntity : IEntity
{
if (typeof(SoftDeleteEntity).IsAssignableFrom(typeof(TEntity)))
return DefaultFilterSoftDelete<TEntity>();
else return x => true;
}
public static Expression<Func<TEntity, bool>>
DefaultFilterSoftDelete<TEntity>()
where TEntity : IEntity
{
var parameterExpression = Expression.Parameter(typeof(TEntity));
var propertyExpression = Expression.Property(parameterExpression,
"
|
Using Many to many with ef linq expression gave me "Unable to create a constant value of type (type)" |
The Entity Framework can't translate the Contains(product) to SQL code.
Your problem lies here:
discount.Products.Contains(product)
You should search the product by it's ProductID, which should be a
primitive type.
This is a know issue which is documented here: Referencing Non-Scalar
Variables Not Supported :
Referencing a non-scalar variables, such as an entity, in a query is
not supported. When such a query executes, a NotSupportedException
exception is thrown with a message that states "Unable to create a
constant value of type EntityType. Only primitive types ('such as
Int32, String, and Guid') are supported in this context."
|
Why the enum constants must be declared before any other variables and methods declaration in an enum type? |
The ; indicates the end of the enum identnfiers list. Apparently you can
have an empty enum list, but you must have one.
See 8.9.1 of the Java Language Specification:
8.9.1 Enum Constants
The body of an enum type may contain enum constants
|
Cannot Add class in Enum.Extensions namespace, because Enum type (System) is then inavailable |
You will need to change the namespace of the Enum Library. Which is your
first library project having Extensions.
Enum is the Type name and you are using it as a namespace and hence there
is ambiguity.
|
How to convert String to enum value when enum type reference is a Class>? |
Enum.valueOf(yrEnum, myString)
Returns the enum where myString is the name of the enum instance you want.
And yrEnum.values() returns an array of all the different possible Enums
instances.
|
LINQ - "Unable to create constant value of type [type]"? |
Try using LINQ 'Where In', this should solve your problem:
var names = new string[] { "Alex", "Colin", "Danny", "Diego" };
var matches = from person in people
where names.Contains(person.Firstname)
select person;
OR
var matches = from person in people
where person.Firstname == "Alex" ||
person.Firstname == "Colin" ||
person.Firstname == "Danny" ||
person.Firstname == "Diego"
select person;
http://blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx
|
Nhibernate throws Object of type 'System.Linq.EnumerableQuery`1[Entity]' cannot be converted to type 'System.Linq.IQueryable`1[System.Object[]]' |
.AsQueryable() will wrap the given IQueryable from NH needlessly into a new
Queryable but since NH will by default use object arrays as results and
transform it later it will fail casting.
Also Selecting the user into another User will prevent changetracking and
is needless copying.
repo.GetAll().Where(f => f.Id == id).FirstOrDefault(); should be enough
or even better because of the sessioncache usage
var user = session.Get<User>(id);
if (user == null)
// user with given Id does not exist
|
Java Enum as generic type in Enum |
In your method implementatopm PerspectiveCommands is not the enum but your
type parameter, which often is called T. It thus shadows the enum of the
same name like axtavt already said, thus PERSPECTIVE is unknown here.
Your abstract method declaration is fine but you might use a slightly
different approach.
public void test(PerspectiveCommands command) would not work, since this
method would not override the generic version. The reason is that with the
generic version the type is inferred from the parameter and thus you could
pass any enum.
However, I assume you have an interface or abstract class which defines the
abstract method. So try something like this:
interface TestInterface<T extends Enum<T>>
{
public abstract void test(T command);
}
class TestImpl implements Tes
|
LINQ/LAMBDA filter query by date |
You could try this:
var myData = myTable
.Where(t => t.Comp.Equals("IBM")
&& (Convert.ToInt32(t.Year) < 2013
|| (Convert.ToInt32(t.Year) == 2013
&& Convert.ToInt32(t.Quarter) <= 2)));
Or this:
var myData = myTable
.Where(t => t.Comp.Equals("IBM")
&& String.Compare(t.Year + "" + t.Quarter, "20131") <=
0 );
|
The conversion of type 'TimeSpan' to type 'Date' is not valid.vb.net |
This is a double question;
You allready asked it here: manipulate DataGridView
I've asked you to strip out the non relative stuff, and you also did not do
anything with the previous question.
|
Unable to cast object of type 'System.Linq.OrderedEnumerable`2[***]' to type 'System.Collections.Generic.IEnumerable`1[***]' |
You're trying to convert a collection of DirectoryToken to a collection of
Token.
This is called a covariant conversion, and it's only supported in .Net 4.0
or later.
If you can't upgrade, you can call .Cast<Token>() to create a new
IEnumerable<T> instance (actually an iterator) that casts each object
to the desired type.
Under no circumstances do you need an explicit cast operation.
|
LINQ To XML error: type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select' |
The problem is with your closing parenthesis - you've got it at the end of
the ToList() call, when you meant to put it at the end of the object
initializer. Also, you're not actually calling the method - you're just
specifying a method group. Finally, you can let type inference work out the
type argument for you:
List<Data> dogs = (from q in doc.Descendants("dog")
where (string)q.Attribute("name") == dogName
select new Data
{
name = q.Attribute("name").Value,
breed = q.Element("breed").Value,
sex = q.Element("sex").Value
}).ToList();
|
OrderBy selector fails while projecting anonymous type |
The query variable name hints that you may be using Entity Framework, LINQ
to SQL or some other IQueryable<T> based API. You are passing the
selector as Func. The underlying query provider cannot translate Func to
SQL (or any other language, whatever you may be using).
Change the type of selector to Expression<Func<Product,
string>> (the rest can remain the same, because lambda expressions
can be interpreted either as a delegate or an expression tree. That's why
you can's use var with lambdas - the compiler just can't tell if you want
the lambda to be a delegate or expression tree) and see if that fixes your
problem. You haven't provided enough information for me to be 100% sure,
but it should. The OrderBy overloads accepting an Expression should be able
to walk the expr
|
Custom OrderBy extension method fails while projecting anonymous type |
The problem is not that it's part of an anonymous type - the problem is
that you don't actually call OrderByWithDirection directly... instead, you
build up an expression tree within the projection and that expression tree
contains a reference to OrderByWithDirection, which LINQ to SQL (or EF, or
whatever) doesn't know about.
I can't think of any nice fix for this other than an expression tree
visitor which goes through the expression tree and replaces the call with
either OrderBy or OrderByDescending based on the second argument - which
would have to be a constant, of course. Even that's going to be far from
trivial.
To be honest, I would probably take a low-tech approach - keep as much of
the query the same as you can, and then conditionally call OrderBy or
OrderByDescending at the end:
|
Closed type classes |
I believe the answer is a qualified yes, depending on what you're trying to
achieve.
You can refrain from exporting the type class name itself from your
interface module1, while still exporting the names of the type class
functions. Then no one can make an instance of the class because no one can
name it!
Example:
module Foo (
foo,
bar
) where
class SecretClass a where
foo :: a
bar :: a -> a -> a
instance SecretClass Int where
foo = 3
bar = (+)
The downside is no one can write a type with your class as a constraint
either. This doesn't entirely prevent people from writing functions that
would have such a type, because the compiler will still be able to infer
the type. But it would be very annoying.
You can mitigate the downside by providing another emp
|
How to set the value of an enum type? |
Directions is a set of elements of type TDirection.
To see if it contains dirNorth, do dirNorth in Directions. The result of
using the in operator is a boolean; dirNorth in Directions is true iff the
set Directions contains the element dirNorth.
To make sure dirNorth is included in Directions, do Directions :=
Directions + [dirNorth].
To make sure dirNorth is not included in Directions, do Directions :=
Directions - [dirNorth].
To set Directions to a particular value, simply assign: Directions :=
[dirNorth, dirSouth].
Formally, + computes the union of two sets; - computes the set difference
of two sets. * computes the intersection of the two operands.
You also have the nice Include and Exclude functions: Include(Directions,
dirNorth) does the same thing as Directions := Directions +
|
C++ lambda return type not what expected |
Thanks to the comments, I have figured out the solution to my problem.
Here is how I initialized temp with a lambda function if anyone is curious:
auto num = data.size();
auto temp = [num](){
vector<string> temp;
for(int i = 0; i < num; ++i){
temp.push_back("");
}
return temp;
}();
My problem was that I was equating the lambda with its return - two
separate things.
...Although, as mentioned in the comments, vector<string>
temp(data.size(), ""); is probably the best (most succint) way.
|
Is there a way to get the enum type from and ordinal value? |
The simplest approach is:
xyzType xyz = xyzType.values()[ordinalValue];
However, this will create a new array each time. An alternative would be to
cache it within the enum:
public enum Xyz {
Foo, Bar;
private static final Xyz[] VALUES = values();
public Xyz fromOrdinal(int ordinal) {
return VALUES[ordinal];
}
}
|
Using typedef enum as a new type |
When you define a type with typedef, you can use it wherever a type can be
used. It's treated as if you'd used the type that was defined. So:
nodeType *list;
is equivalent to:
enum {Integer, String, List, Nil} *list;
|
enum type and its linkage in C |
The enum type and its values simply don't exist anymore after compilation.
enum is a C construct, not anything to do with how your machine actually
operates. You're perfectly allowed to give a particular enumeration type
different values in different translation units. There's nothing the
linker is going to be able to do about it later.
If you want to ensure that your enum type is consistent, you should
probably put a single definition of it in a common header included by all
translation units.
Editorial note: Don't use identifiers with leading underscores. They're
reserved by the implementation.
|
Enum type Warning in C |
You are using int type where enum PinSel_BasicMode type is required. While
enums and ints are usually interchangeable, they are different types.
Value 0 is not an enum value. PINSEL_BASICMODE_NPLU_NPDN is. It is only 0
through definition.
Should the enum declaration change and PINSEL_BASICMODE_NPLU_NPDN was equal
to 1, your code would be invalid.
|
What's better? Enum or Type checking? |
I commonly do like this:
1: Define some kind of key, for instance like you already suggest:
TypeInfoEnum typeInfo
{
...
}
2: Create a Dictionary with parsers declared like this:
Dictionary<TypeInfoEnum, Func<XDocument, IBase>>
3: Implement your public method like this:
public class Parser
{
IBase Parse(XDocument xDocument)
{
TypeInfoEnum key = GetKeyForXDocument(xDocument);
IBase x = DictionaryWithParsers[key](xDocument);
return x;
}
}
I ignored error handling and the implementation for the GetKeyForXDocument
method, but that shouldn't be very difficult.
Your API consumer would consume it like this:
void SomeConsumingMethod()
{
...
IBase x = serviceObject.Parse(xDocument);
// Members declared in IBase:
x.SomeMet
|
What is operation in enum type? |
That's a bitwise shift operation. It is used so that you can set one or
more flags from the enum. This answer has a good explanation: Why use
the Bitwise-Shift operator for values in a C enum definition?
Basically, it's so that one integer can store multiple flags which can be
checked with the binary AND operator. The enum values end up looking like
this:
typedef enum {
NSStreamEventNone = 0, // 00000
NSStreamEventOpenCompleted = 1 << 0, // 00001
NSStreamEventHasBytesAvailable = 1 << 1, // 00010
NSStreamEventHasSpaceAvailable = 1 << 2, // 00100
NSStreamEventErrorOccurred = 1 << 3, // 01000
NSStreamEventEndEncountered = 1 << 4 // 10000
};
So you can say:
// Set two flags with the binary
|
Why Lambda Function in C++0x return type has to be auto? |
You seem to be getting confused between the result of the function and the
function itself. On this line
auto result = [&val1, &val2](){return (val1 + val2);};
you are creating a lambda function (on the right side of the =), and
assigning it to a variable called result. The auto there is for the type
of the variable holding the lambda function, not the return type of the
lambda function.
If you wanted to make the return type be explicit, it would be done like
this:
auto result = [&val1, &val2]() -> int {return (val1 + val2);};
If you wanted to make the type of result more explicit, you can use
std::function:
std::function<int()> result = [&val1, &val2]() {return (val1
+ val2);};
Also, since result is a function, you would use result like this:
s
|
Lambda Reflection with generic type (Where(ReflectedLambda)) |
well, you may have some flaws in your architecture (hard to say with the
sample code)... Anyway, you could call your method using reflection.
var method = typeof(<Type with the
method>).GetMethod("GenerateExpression");
var genericMethod = method.MakeGenericMethod(sourceObjectType.GetType());
var result = genericMethod.Invoke(null, new[]{regName, idEscrit});//null if
method is in a static class
but I would really look first at architecture.
|
Cannot convert lambda expression to delegate type |
I think you just have your syntax off a bit. Try:
public user GetUser(int intUserID)
{
using (var context = new iomniEntities())
{
user u = context.users.Where(u => u.userID ==
intUserID).FirstOrDefault();
return u;
}
}
Or to hold onto your version, it just needs touched up:
public user GetUser(int intUserID)
{
using (var context = new iomniEntities())
{
user u = context.users.FirstOrDefault(user => user.userID ==
intUserID);
return u;
}
}
|
MVC Cannot convert lambda expression to type because it is not a delegate |
Found what happens.
The asp.net tags are not allowed in the SetContent() that way.
The correct way to do it is:
CBsettings.SetContent(() => {
ViewContext.Writer.Write("<h1>Hello World</h1>");
...
});
So sad the intellisense doesn't give a clue about what is wrong.
|
How to serialize a closed immutable type with protobuf-net? |
Yes. Note that many immutable types will be handled by the "auto tuple"
code - if it has a constructor that accepts parameters that look just like
the public members, it can infer the behaviour from that.
Other than that, you can write your own DTO that has whatever layout /
members you need, and add conversion operators (implicit or explicit) to
and from your custom DTO and the target type (Font in this case). Your
operator would have the code to get from one to the other. Then call:
RuntimeTypeModel.Default.Add(typeof(Font), false)
.SetSurrogate(typeof(YourCustomDTO));
The serializer will use the operators to change between the two types, and
use the custom DTO on the wire.
Watch out for the incoming value to the operator being null!
|
What's the point of lambda expression in OrderBy? |
When you order a collection it doesn't change it's type, hence
IEnumerable<Something> somethings = ...;
var strings = somethings.OrderBy(a => a.StringProperty);
results in an IEnumerable<Something>, you have to select the property
to change the type:
IEnumerable<String> strings = somethings
.OrderBy(s => s.StringProperty)
.Select(s => s.StringProperty);
So why am I enforced to use the lambda expression in the OrderBy
command?!
Because Enumerable.OrderBy is a method that needs an argument.
|
Is there a way to cast this enum to proper type |
You can do this:
void SetOptions()
{
DropDownList.Items.Clear();
var options = Enum.GetValues(ListType); // need to cast this to type of
ListType
foreach (var o in options)
{
var item = new ListItem(o.Description(), o.ToString());
item.Tag = o;
DropDownList.Items.Add(item);
}
}
Then you can get the type from the Tag property of whatever list item is
selected.
|
enum Not Type Checked by Compiler? |
Actually enum options are treated as NSInteger. So thatThingX has the value
of 0 by default. When you assign self.thisThing = thatThingX;
self.thisThing got the value of 0. So it will become ThisThingA. That's why
there are no warnings.
|
Extracting enum type from propertyType |
You can just .ToString() the EnumTestData property, like this:
var test = new TestData();
test.EnumTestData = TestEnum.Test1;
var dummy = test.EnumTestData.ToString();
Note: dummy will be "Test1".
|
Bind a char to an enum type |
Unfortunately there is not much you can do to clean this up. If you have
access to the C++11 strongly typed enumerator feature, then you could do
something like the following:
enum class Section : char {
START = 'S',
MID = 'M',
END = 'E',
};
And then you could do something like:
std::cout << static_cast<char>(Full[i]) << std::endl;
However, if you do not have access to this feature then there's not much
you can do, my advice would be to have either a global map
std::map<Section, char>, which relates each enum section to a
character, or a helper function with the prototype:
inline char SectionToChar( Section section );
Which just implements the switch() statement in a more accessible way, e.g:
inline char SectionToChar( Section section ) {
|
c# string text, enum type |
You could use TryParse :
Category outCategory;
Enum.TryParse(this.category, out outCategory)
switch(outCategory)
{
case Category.Part:
//I want to call here function HandlePart with my line as a
parameter
HandlePart(newStr);
break;
case Category.Escape:
//Here I want to call Function HandleEscape for line with
"Escape" word
HandleEscape(newStr);
break;
default:
// Needs to be handled
}
|