Select multiple column in Linq using List - linq

I have a DropDownList and I fill it using linq. The code example below is working.
ddlPortal.DataSource = from rows in db.Portals select new
{rows.Id, rows.PortalName};
But I need to use it with List variable. What's the problem about the code below?
ddlPortal.DataSource = new List<string>(from rows in db.Portals select new {rows.Id.ToString(), rows.PortalName});
By the way I need to retrieve two columns for DataValueField and DataTextField of DropDownList .

That's not a List<string> but a list of an anonymous type. Use var:
var dataSource = db.Portals
.Select(rows => new {Id = rows.Id.ToString(),Portal = rows.PortalName} )
.ToList();
ddlPortal.DataSource = dataSource;

Related

how to update observable collection group

I have implemented group observable collection like below.
Grouped Property
private ObservableCollection<Grouping<String, Request>> _groupedList = null;
public ObservableCollection<Grouping<String, Request>> GroupedList {
get {
return _groupedList;
}
set {
_groupedList = value;
RaisePropertyChanged(() => GroupedList);
}
}
Creating List
var list = new List<Request>();
var grouped = from Model in list
group Model by Model.Done into Group
select new Grouping<string, Request>(Group.Key, Group);
GroupedList = new ObservableCollection<Grouping<string, TModel>>(grouped);
Now i need to update one item in the list without reloading full list for performance.
i did tried like this , mylist.FirstOrDefault(i => i.Id== mymodel.Id); Not worked for me.
I need to pick that particular item and edit and update into the list again using linq or something but i stuck here for group observable collection no efficient details to do this., anybody having idea about this help please.
And finally i get updated single item, but i need to do that without
GroupedList = new ObservableCollection<Grouping<string, TModel>>(grouped);
Because everytime it create new list and bind into my view.Thats again big performance though.
Thanks in advance.
What I understand from your question is that you want to push an updated group without overwriting the entire ObservableCollection.
To do that:
var targetGroup = GroupedList.FirstOrDefault(i => i.Id == mymodel.Id);
var targetIndex = GroupedList.IndexOf(targetGroup);
var modifiedGroup = ... //Do whatever you want to do
GroupedList[targetIndex] = modifiedGroup;
This will trigger a 'replace' operation of the target grouping.

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,
});

Binding hardcoded values and databases values into one dropdownlist

I have a drop down list in C# asp.net MVC3 razor engine.
I need to load values to that dropdownlist from one of my tables in my database and some values are hard coded.
So I need to get both kind of values into one dropdown list.
I can do them separately.
This is how my view is :
#Html.DropDownListFor(model => model.MyTransaction.Status, new MultiSelectList(ViewBag.MyStatusId, "ID", "Name"))
My Model where enums are created :
public enum Ntypes{
halfday
casual
}
My Controller :
ViewBag.MyTransaction = db.LeaveTypes.ToList(); //get the table values to drop down
//then even I can get the hard coded values separately ............
ViewBag.MyTansaction = (from NewLeaveTypes t in Enum.GetValues(typeof(Ntypes))
select new { ID = t, Name = t.ToString()).ToList();
But cant get both values into one dropdownlist.
Plzzzz Help.
Thanks...........
You could concatenate the 2 lists together:
var nTypes = Enum
.GetValues(typeof(Ntypes))
.Select(t => new LeaveType { ID = t, Name = t.ToString())
.ToList();
ViewBag.MyTransaction = db.LeaveTypes.ToList().Concat(nTypes);
and then in the view:
#Html.DropDownListFor(
model => model.MyTransaction.Status,
new SelectList(ViewBag.MyTransaction, "ID", "Name")
)

getting strongly typed column names from datacontext

Is it possible to get the column names directly from a datacontext? Below I'm just hard coding the DataTextField and DataValueField, but I'd like to be able to get them from the datacontext if possible. What is the recommended way of getting the column names in a strongly-typed way?
DataClassesDataContext db = new DataClassesDataContext(WebConfigurationManager.ConnectionStrings[connstring].ConnectionString);
drdPriority.DataSource = db.Tasks;
drdPriority.DataTextField = "TaskDescription";
drdPriority.DataValueField = "TaskId";
drdPriority.DataBind();
Try the following code:
using (DataContext1.DataContext1 dc = new DataContext1.DataContext1()) {
var q = dc.Mapping.GetTables();
foreach (System.Data.Linq.Mapping.MetaTable table in q) {
List names = new List();
foreach (System.Data.Linq.Mapping.MetaDataMember member in table.RowType.DataMembers) {
names.Add(member.Name);
}
//Process the names here
}

Linq Query Using DataTable with Paging

I have a Linq query that I copy to a DataTable which is then used to populate a gridview. I am using a group by "key" and "count" which I evaluate in the aspx page for a master/detail gridview with a repeater.
The problem that I am encountering is that the gridview datasource and bind to the datatable is not presenting me with any additional pages that are part of the data.
My query is:
// Using Linq generate the query command from the DataTable
var query = from c in dtDataTable_GridView.AsEnumerable()
group c by c.Field<string>("CLIN") into g
select new
{
Key = g.Key,
Count = g.Count(),
Items = from i in g
select new
{
CLIN = i.Field<string>("CLIN"),
SLIN = i.Field<string>("SLIN"),
ACRN = i.Field<string>("ACRN"),
CLINType = i.Field<string>("CLINType"),
Option = i.Field<string>("Option"),
Unit = i.Field<string>("Unit")
}
};
// Use extension methods to create new DataTable from query
dtTaskOrderTable = query.CopyToDataTable();
// Set the datasource
gridview1.DataSource = dtTaskOrderTable;
// Bind to the GridView
gridview1.DataBind();
If I use the original datatable (dtDataTable_GridView) directly I have paging but once I do the Linq Query and copy it back to a new datatable (dtTaskOrderTable) I lose the paging feature.
Also how do I get a value from a column name ("Option" for instance) if it is part of "Items"?
Any help would be appreciated.
Thanks,
ChrisB
Please disregard the previous answer I will delete it
It requires ICollection interface for paging.
Neither IEnumerable nore IQuerable will not work
List<(Of <(T>)>) will work as Lists implement Icollection interface
So you need
gridview1.DataSource = dtTaskOrderTable.ToList();

Resources