Why am I getting "Cannot convert lambda expression to type 'string' because it is not a delegate type"? - asp.net-mvc-3

I have a simple table called LookupTable with two fields: Id (int) and Description (nvarchar) that I want to use to populate a drop down list.
The following code gives me the error:
IEnumerable<SelectListItem> items =
_entities.LookupTable.Select(t=> new SelectListItem {Value = t.Id,
Text = t.Description } );
I have a using System.Linq; statement already, and I get a runtime error if I try t.Id.ToString().
I must be missing something simple, right?

It is not clear from your question what is the type of _entities.LookupTable. If we suppose that it is some IQueryable<SomeModel> or IEnumerable<SomeModel> where SomeModel contains two properties Id and Description, you must ensure that you are properly converting those two values to string as the Value and Text properties of a SelectListItem are strings.
You may also try to eagerly execute the query by calling .ToString():
var items = _entities
.LookupTable
.ToList()
.Select(t => new SelectListItem
{
Value = t.Id.ToString(), // <-- notice that you might need a ToString if the Id property is integer
Text = t.Description
});

Related

what is a projection in LINQ, as in .Select()

I typically do mobile app development, which doesn't always have .Select. However, I've seen this used a bit, but I don't really know what it does or how it's doing whatever it does. It is anything like
from a in list select a // a.Property // new Thing { a.Property}
I'm asking because when I've seen code using .Select(), I was a bit confused by what it was doing.
.Select() is from method syntax for LINQ, select in your code from a in list select a is for query syntax. Both are same, query syntax compiles into method syntax.
You may see: Query Syntax and Method Syntax in LINQ (C#)
Projection:
Projection Operations - MSDN
Projection refers to the operation of transforming an object into a
new form that often consists only of those properties that will be
subsequently used. By using projection, you can construct a new type
that is built from each object. You can project a property and perform
a mathematical function on it. You can also project the original
object without changing it.
You may also see:
LINQ Projection
The process of transforming the results of a query is called
projection. You can project the results of a query after any filters
have been applied to change the type of the collection that is
returned.
Example from MSDN
List<string> words = new List<string>() { "an", "apple", "a", "day" };
var query = from word in words
select word.Substring(0, 1);
In the above example only first character from each string instance is selected / projected.
You can also select some fields from your collection and create an anonymous type or an instance of existing class, that process is called projection.
from a in list select new { ID = a.Id}
In the above code field Id is projected into an anonymous type ignoring other fields. Consider that your list has an object of type MyClass defined like:
class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
Now you can project the Id and Name to an anonymous type like:
Query Syntax:
var result = from a in list
select new
{
ID = a.Id,
Name = a.Name,
};
Method Syntax
var result = list.Select(r => new { ID = r.Id, Name = r.Name });
You can also project result to a new class. Consider you have a class like:
class TemporaryHolderClass
{
public int Id { get; set; }
public string Name { get; set; }
}
Then you can do:
Query Syntax:
var result = from a in list
select new TemporaryHolderClass
{
Id = a.Id,
Name = a.Name,
};
Method Syntax:
var result = list.Select(r => new TemporaryHolderClass
{
Id = r.Id,
Name = r.Name
});
You can also project to the same class, provided you are not trying to project to classes generated/created for LINQ to SQL or Entity Framework.
My summary is it takes results (or a subset of results) and allows you to quickly restructure it for use in the local context.
The select clause produces the results of the query and specifies the
"shape" or type of each returned element. For example, you can specify
whether your results will consist of complete Customer objects, just
one member, a subset of members, or some completely different result
type based on a computation or new object creation.
Source: http://msdn.microsoft.com/en-us/library/bb397927.aspx
There are a lot of possible uses for this but one is taking a complex object which of many other contains a property that is a string -- say Name -- and allows you to return an enumeration with just the entries of Name. I believe you can also do the opposite -- use that property ( for example) and create / return new type of object while passing in a property or properties.
It means "mapping". Map each element of a sequence to a transformed sequence. I hadn't comprehended its meaning before I looked at the image.
Where does the meaning of the word come from?
Simply, math! https://mathworld.wolfram.com/Projection.html

mvc3 INT in a IEnumerable selectlistitem

I have a selectlistitem that gathers data from the database and inserts it into a dropdownlist. All of that works but I can't seem to make the INT work for instance if I write this.. etc. The issue is with the ArticleID
IEnumerable<SelectListItem> items = db.Articles.Where(c=>c.RegistrationID==getid)
.Select(c => new SelectListItem
{
Value =c.ArticleID +"/"+ c.title,
Text = c.ArticleID + "/" + c.title
});
ViewBag.articles = items;
I get the error Unable to cast the type 'System.Int32' to type 'System.Object' and
then my dropdownlist gets highlighted which is
#Html.DropDownList("article1",(IEnumerable<SelectListItem>)ViewBag.articles)
I obviously can't do c.ArticleID.Tostring() , so how can I fix this issue ? If I take the ArticleID out everything works correctly but I need that in there..
You would actually use c.ArticleID.ToString(). The reason is that you're concatenating a string together, therefore need string values to do so. Value and Text are both string types so it makes sense that you need strings.

Returning Linq query results into a List object (based on condition)

I need to return a number of Linq query results into a List object based on a foreign key value. What is the syntax for doing this? I am new to using Linq, so below is my best guess so far. I receive an error in the .Where() "clause" stating "The name 'pt' does not exist in the current context. Any help would be greatly appreciated!
List<AgentProductTraining> productTraining = new List<AgentProductTraining>();
var prodCodes = productTraining.Select(pt => new[]
{
pt.ProductCode,
pt.NoteId,
pt.ControlId
})
.Where(pt.CourseCode == course.CourseCode);
You would need to switch the locations of where and select if you're using extension methods:
var prodCodes = productTraining.Where(pt => pt.CourseCode == course.CourseCode)
.Select(pt => new SomeRandomType
{
ProductCode = pt.ProductCode,
NoteId = pt.NoteId,
ControlId = pt.ControlId
});
I also recommend, as you can see above, that you create a type for that select statement so that you're not relying on anonymous types. You should put in into an object type that you know everything about.
Also, if CourseCode is a string, that should be pt.CourseCode.Equals(course.CourseCode).

Filter SelectListItem value using some condition

I have one SelectListItem for DropDownList. I have to filter based on some condition. If I try adding the condition then its gives me an error like this (LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression). I ll be adding that code here. Please guide me to solve this.
Code
IEnumerable<SelectListItem> IssueId = (from txt in Db.Issues where txt.BibId == BibId
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true,
});
SelectList IssueIds = new SelectList(IssueId, "Value", "Text");
ViewBag.IssueId = IssueIds;
Thanks
Try this:
LINQ2EF does not know ToString() but after AsEnumerable() you'll get a local collection when ToString() is implemented.
IEnumerable<SelectListItem> IssueId =
(from txt in Db.Issues.Where(e => e.BibId == BibId).AsEnumerable()
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true
});
Linq To Sql can't generate TSQL for txt.Id.ToString()
You will need to iterate the result instead after executing the query, or cast to Enumerable as xeondev suggests.
That extension does not seem to be sorted by linq to Entities but you could just do the mapping once you have the issues, e.g.
var issues = (from issue in Db.Issues
where issue .BibId == BibId
select issue ).ToList();
IEnumerable<SelectListItem> IssueId = (from txt in issues
where txt.BibId == BibId
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true,
});

Index was out of range when expression converted to linq expression

I am creating a collection of select list items from my userGroupsRepository.
I know that there are two records.
Is there something what i am doing wrong?
At first i have written following code as i thought this is a faster way to get my select list item collection, where i have "this._userGroupRepository.All" as IQueryable
my collection is:
List<SelectListItem> listItems = this._userGroupRepository.All.Select(
userGroup => new SelectListItem() {
Text = userGroup.GroupName,
Value = userGroup.UserGroupId.ToString()
}).ToList();
this implementation however results with
Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
and here i have my implementation of collection with rewriting it as foreach
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (UserGroup userGroup in this._userGroupRepository.All)
{
listItems.Add(new SelectListItem(){
Text = userGroup.GroupName,
Value = userGroup.UserGroupId.ToString()});
}
Does it help to make an Enumerable of your Queryable?
this._userGroupRepository.All.AsEnumerable().Select(

Resources