I am trying to add an item to an IEnumerable SelectList. I have an initial query that populates my list, I then have a query to check to see if an item called "INFORMATIONAL" exists. If not, I need to add it to the list returned from my initial query. Here is my code. It does not like list.Add(newItem). Any assistance would be appreciated. Thanks
public IEnumerable<SelectListItem> GetCategoriesByAccountID(string AccountID)
{
IEnumerable<SelectListItem> list = null;
using (var context = new AMPEntities())
{
// Queries DB for list of categories by AccountID
var query = (from ca in context.CustomAlerts
where ca.AccountID == AccountID
orderby ca.AlertCategory
select new SelectListItem { Text = ca.AlertCategory, Value = ca.AlertCategory }).Distinct();
list = query.ToList();
// Checks list to see if "INFORMATIONAL" already exists
var item = (from l in list
where l.Value == "INFORMATIONAL"
select new SelectListItem { Text = l.Text, Value = l.Value }).FirstOrDefault();
// If "INFORMATIONAL" is not present add it to list
if (item == null)
{
var newItem = new SelectListItem { Text = "INFORMATIONAL", Value = "INFORMATIONAL" };
list.Add(newItem);
}
}
return list;
}
The problem is that your variable is of type IEnumerable<SelectListItem>. Either change it to List<SelectListItem> or use another variable.
public IEnumerable<SelectListItem> GetCategoriesByAccountID(string AccountID)
{
List<SelectListItem> list = null;
using (var context = new AMPEntities())
{
// Queries DB for list of categories by AccountID
var query = (from ca in context.CustomAlerts
where ca.AccountID == AccountID
orderby ca.AlertCategory
select new SelectListItem { Text = ca.AlertCategory, Value = ca.AlertCategory }).Distinct();
list = query.ToList();
// Checks list to see if "INFORMATIONAL" already exists
var item = (from l in list
where l.Value == "INFORMATIONAL"
select new SelectListItem { Text = l.Text, Value = l.Value }).FirstOrDefault();
// If "INFORMATIONAL" is not present add it to list
if (item == null)
{
var newItem = new SelectListItem { Text = "INFORMATIONAL", Value = "INFORMATIONAL" };
list.Add(newItem);
}
}
return list;
}
Essentially, you cannot, because IEnumerable does not necessarily represent a collection to which items can be added. See this question on SO.
How can I add an item to a IEnumerable<T> collection?
Here is something I came up with that might be helpful to someone. Maybe even me at a later date. Take a look at the last line of code.
CostCenterHeaders CostHeaders = CostCenterHeaders.GetCostCenterHeaders(ClientNumber);
List<SelectListItem> Level1Header = new List<SelectListItem>();
if (CostHeaders.Level1Heading !=null)
{
Level1Header.Add(new SelectListItem { Text = "All " + CostHeaders.Level1Heading + " Centers", Value = "" });
List<HierarchyLevel> HierarchyLevels = HierarchyLevel.GetHierarchyByLevel(ClientNumber);
Level1Header.AddRange(HierarchyLevels.Select(x => new SelectListItem() { Value = x.LevelID, Text = x.LevelDescr }).ToList());
}
Related
How to set selected true from contains list string in linq ???
I want to set selected true if some field is same from variabel list string. this is my code for my case.
string detail = Request.QueryString["detail"];
List<string> KdUser = new List<string>();
if (detail != null) {
KdUser = (from u in db.TUserSelecteds where u.detail_guid_edis == new Guid(detail) select u.kode_user).ToList();
}
// KdUser = [0]U002,[1]U001,[2]U003
List<SelectListItem> items = (from us in db.Users
where us.ApplicationId == "TMS-APP-03" && us.IsActive == 1
orderby us.NamaKaryawan
select new SelectListItem()
{
Text = us.NamaKaryawan,
Value = us.KodeUser
//Selected = true => If (Value Contains KdUser)
}).ToList();
I hope you understand what i mean. thanks
List<SelectListItem> items = (from us in db.Users
where us.ApplicationId == "TMS-APP-03" && us.IsActive == 1
orderby us.NamaKaryawan
select new SelectListItem()
{
Text = us.NamaKaryawan,
Value = us.KodeUser
Selected = KdUser.Contains(us.KodeUser)
}).ToList();
New to C# and appreciate any help. The issue is that I need to filter the results of my api call against an array (using an "allowedA" and "allowedB" array.) I don't know how to edit the lambda expression to check against the loop.
var activities = await _restClientTaxonomy.GetTaxonomyFullAsync(TAXONOMY_CLASSIFICATIONID_FOR_ACTIVITY);
var activityTypes = await _restClientTaxonomy.GetTaxonomyFullAsync(TAXONOMY_CLASSIFICATIONID_FOR_ACTIVITY_TYPES);
var documentEventxx = activities.Select(type => type.Id);
long [] allowedA = new long []{ 7137, 40385637};
long [] allowedB = new long []{ 7137, 40385637};
foreach (long value in documentEventxx)
{
foreach (var item in allowed)
{
if (item == value) {
//These are the values I am looking for -> values that are part of the documentEventxx and allowedB.
}
}
}
var result = activityTypes.Select(type => new CategoryViewModel
{
Id = type.Id,//This is where I want to add only items that are in the allowedA array
Text = type.Name,
Types = activities.Where(a => a.ParentId == type.Id).Select(t => new TaxonomyMemberTextItem
{
Id = t.Id, //This is where I want to add only items that are in the allowedB array
Text = t.Name
}).ToList()
}).ToArray();
I have been reading about lambda expressions and foreach loops so please don't just post a random link.
Thanks in advance.
Filter the values before Selecting.
activityTypes.Where(x=>allowedA.Contains(x.Id)).Select(type => new CategoryViewModel
{
Id = type.Id,
Text = type.Name,
Types = activities.Where(a => a.ParentId == type.Id && allowedB.Contains(a.Id)).Select(t => new TaxonomyMemberTextItem
{
Id = t.Id,
Text = t.Name
}).ToList()
})
To filter you use .Where. You .Select to create a list of new types. So in order to filter, then create the lists of objects you want:
var result = activityTypes.Where(type=>isAllowed(type.Id)).Select(type => new CategoryViewModel
{
Id = type.Id,//This is where I want to add only items that are in the allowedA array
Text = type.Name,
Types = activities.Where(a => a.ParentId == type.Id&&isAllowed(a.Id)).Select(t => new TaxonomyMemberTextItem
{
Id = t.Id, //This is where I want to add only items that are in the allowedB array
Text = t.Name
}).ToList()
}).ToArray();
How do I set the selected value on a select list.
For example, say i'm displaying an existing client and on the form it has a dropdown list for "Gender", I want "Male" to be selected (if that what was saved in the db) how do I do this?
When I'm building my model im doing something like
public ActionResult Edit(string id)
{
var client= _clientService.FindById(id);
var model = new ViewModels.Client()
{
GenderId= client.GenderId,
GenderList= CreateGenderList(GenderId)
};
}
private IEnumerable<SelectListItem> CreateGenderList(int gId)
{
var list = Enum.GetValues(typeof(DomainObjects.Client.GenderList))
.Cast<DomainObjects.Client.GenderList>()
.Select(v => new SelectListItem { Text = v.ToString(), Value = ((int)v).ToString() });
//Need to set the selected value, how?
return list.ToList();
}
Thank you in Advance.
You should make use of the additional SelectListItem.Selected property, and set this to true. For example:
var list = Enum.GetValues(typeof(DomainObjects.Client.GenderList))
.Cast<DomainObjects.Client.GenderList>()
.Select(v => new SelectListItem {
Text = v.ToString(),
Value = ((int)v).ToString()});
var maleGenderItem = list.Single(x => x.Text == "Male");
maleGenderItem.Selected = true;
This did it
var list = Enum.GetValues(typeof(DomainObjects.Client.GenderList))
.Cast<DomainObjects.Client.GenderList>()
.Select(v => new SelectListItem { Text = v.ToString(), Value = ((int)v).ToString(), Selected = gName.ToString() == ((int)v).ToString() });
return list.ToList();
I have created a function on my restaurant review site that finds the cuisine of the last review and then finds other reviews of the same cuisines with a greater average score and then saves the restaurant id of those reviews into a table on the database. However I keep on getting the error:
Cannot assign method group to an implicitly-typed local variable.
on the line restaurantid = choices.Any help would be grateful.
var averagescore = db.Reviews
.Where(r => r.Cuisine == review.Cuisine)
.Average(r => r.score);
var choices = (from r in db.Reviews
where r.score <= averagescore
select r.RestaurantId).ToList;
foreach (var item in choices)
{
var suggestion = new Suggestion()
{
id = review.id,
Userid = review.UserId,
restaurantid = choices
};
db.Suggestions.Add(suggestion);
db.SaveChanges();
}
Following line:
var choices = (from ...).ToList;
Should be:
var choices = (from ...).ToList();
Secondly, it looks to me that restaurantid is of type int. With your code you're assigning a List<int> to the int. This should be item, from the loop.
You need to make the following change:
var averagescore = db.Reviews
.Where(r => r.Cuisine == review.Cuisine)
.Average(r => r.score);
var choices = (from r in db.Reviews
where r.score <= averagescore
select r.RestaurantId).ToList;
foreach (var item in choices)
{
var suggestion = new Suggestion()
{
id = review.id,
Userid = review.UserId,
restaurantid = item //here was your problem, you need to assign an id not a list of ids
};
db.Suggestions.Add(suggestion);
db.SaveChanges();
}
Have you tried like this:
var choices = (from r in db.Reviews
where r.score <= averagescore
select r).ToList;
foreach (var item in choices)
{
var suggestion = new Suggestion()
{
id = item.id,
Userid = item.UserId,
restaurantid = item.Restaurantid
};
db.Suggestions.Add(suggestion);
db.SaveChanges();
}
I'm working with entity framework database and I want to populate my dropdownlist from a table but in right order.
Right now i'm using the code:
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
List<object> sDataValue = new List<object>();
sDataValue.Add("- Select -");
sDataValue.Remove("Other");
foreach (var vData in databaseList)
{
sDataValue.Add(vData.SkillName);
}
sDataValue.Add("Other");
DropDownListDB.DataSource = sDataValue.ToArray();
DropDownListDB.DataBind();
This is the Solution
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
orderby p.skill_name != "Other" descending, p.skill_name
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
Remove the entry -Select- from the list and append it as first item to your List<object>:
List<object> sDataValue = new List<object>();
sDataValue.Add("-Select-");
foreach (var vData in databaseList){}
would be the easiest way, I assume.
EDIT
then you will use if/else, maybe and
foreach (var vData in databaseList){} //fill your list
sDataValue.Add("-Other-");
You could add a "section id" to your database: 0 for "-Select-", 2 for "Other", 1 for the rest. Then sort on 1) section ID, 2) name.
But it would be best not to store that "-Select-" at all (it doesn't represent a valid value) and add it in the correct spot after the databind.
Just do this:
Remove -Select- and Other from databaseList like this:
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
&& p.skill_name.ToLower() !="other"
&& p.skill_name.ToLower() !="-select-"
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
and then do this:
DropDownListDB.DataSource = sDataValue.ToArray().OrderBy(s=>s);
DropDownListDB.Items.Insert(0, "-Select-");
DropDownListDB.Items.Add("Other");
if you must bring -Select- and Other field from database, binding them to the DropDownList and then removing them and again inserting them at appropriate location is little expensive.
You simply don't pick those two rows from the database. it will be more efficient.
You can try play with orderby with boolean value
orderby p.skill_name != "Other" descending, p.skill_name
In your code =>
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
orderby p.skill_name != "Other" descending, p.skill_name
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
List<object> sDataValue = new List<object>();
sDataValue.Add("- Select -");
foreach (var vData in databaseList)
{
sDataValue.Add(vData.SkillName);
}
DropDownListDB.DataSource = sDataValue.ToArray();
DropDownListDB.DataBind();