i have the following code that i need to modify with an if statement to say that if something that make result this, or else make it that. here is what i have now:
var result = (from fs in ctx.datFiles
where fs.File_ID == fID
select new
{
LastName = fs.datClaim.LastName,
FirstName = fs.datClaim.FirstName,
}).FirstOrDefault();
DetailsModelView dmv = new DetailsModelView
{
ClaimID = result.ClaimID,
LastName = result.LastName,
FirstName = result.FirstName,
};
i want to do something like:
var result =""
if (something)
{
result = (from fs in ctx.datFiles
where fs.File_ID == fID
select new
{
LastName = fs.datClaim.LastName,
FirstName = fs.datClaim.FirstName,
}).FirstOrDefault();
}
else
{
result = (from fs in ctx.datFiles
where fs.File_ID == 5
select new
{
LastName = fs.datClaim.LastName,
FirstName = fs.datClaim.FirstName,
}).FirstOrDefault();
}
DetailsModelView dmv = new DetailsModelView
{
ClaimID = result.ClaimID,
LastName = result.LastName,
FirstName = result.FirstName,
};
but i keep getting the following error: Cannot implicitly convert type ‘AnonymousType#1’ to ‘string’ when i try to create “result” outside of the LINQ statement.
What do i need to declare result as to make it work, instead of string?
this was just a simple example, my query gets a lot more complicated on the “else” then just the ID change.
Here is a functional program that works:
As you can see I’ve created a dummy anonymous object so that the
var fooknows what object to make. This should obviously be the same anonymous object as you are creating int he two branches of the if statement.It should also be noted that in the above code there doesn’t seem to be any reason not to use
DetailsModelViewdirectly in the linq rather than an anonymous type. It may be your use case is more complex but since there is a simple one to one mapping you can just create yourDetailsModelViewwhere you currently create the anonymous method. Then result can just be defined as beingDetailsModelView.