How to add Items in IEnumerable? - c#

I have this code and I would like to add Item in the list and I am doing like this.
IEnumerable<SelectListItem> note = new List<SelectListItem>();
var selectList = new SelectListItem
{
Text = Convert.ToString(amount.Key),
Value Convert.ToString(amount.Value)
};
note.ToList().Add(selectList);
I am unable to Add item.

The ToList() call creates a brand new list, which is not connected to the original list. No changes you make to the new list will be propagated back to the original.
As for adding, you cannot add items to the IEnumerable<T>. It all depends on that you're trying to do with your code, but why do you use IEnumerable<SelectListItem> instead of IList<SelectListItem>, which has an Add() operation. Since IList<T> is-a IEnumerable<T>, you will be able to pass the note to any method that expects an IEnumerable<T>.

When you say ToList() it's not casting it, it's creating a whole new list and that's what you're adding to.
What you want is to avoid the weird casting you do to start with (make note a List not an IEnumerable) and then add to that directly
List<SelectListItem> note = new List<SelectListItem>()
var selectList = new SelectListItem{Text = Convert.ToString(amount.Key), Value Convert.ToString(amount.Value) }
note.Add(selectList)
Not that it makes any sense to do that but if you really want to assign your list to an IEnumerable to begin with you can still cast it later when you need the added functionality as follow:
IEnumerable<SelectListItem> note = new List<SelectListItem>()
var selectList = new SelectListItem{Text = Convert.ToString(amount.Key), Value Convert.ToString(amount.Value) }
((List<SelectListItem>)note).Add(selectList)

List<SelectListItem> note = new List<SelectListItem>();
var selectList = new SelectListItem
{
Text = Convert.ToString(amount.Key),
Value Convert.ToString(amount.Value)
};
note.Add(selectList);
var notes = note.AsNumerable();

Related

How to use linq instead of foreach loop in c#

I'm trying to find solution for the next situation:
I have array with Item ids
var arrayIds = new long []{1076,2840,4839,3920,..., N};
I have method which returns one Item
public Item getItem(long id) {
return new Item{Id = id, Name = "name"};
}
Here trying to get all Items
var itemList = new List<Item>();
foreach(var id in arrayIds) {
itemList.Add(getItem(id));
}
Is it possible to use Linq here instead of foreach?
I've tried to write something like that
itemList = arrayIds.ForEach(x => getItem(x));
so I have the next error here:
There is no argument given that corresponds to the required formal parameter 'action' of 'Array.ForEach<T>(T[], Action<T>)'
So I don't know how to use Linq correctly.
I've tried to write something like that
itemList = arrayIds.ForEach(x => getItem(x));
ForEach() works on List<T>:
arrayIds.ToList().ForEach(x => getItem(x));
But what you want is:
var itemList = arrayIds.Select(getItem).ToList();
Or if you only want to enumerate the items:
var items = arrayIds.Select(getItem);
Use Select
var itemList = arrayIds.Select(x => getItem(x))

Selected property on SelectListItem not being set by SelectList constructor

I'm creating a SelectList to pass to a Html.DropDownList, but the correct value doesn't seem to be populating
var x = new SelectList(new[] {
new SelectListItem() { Value="1", Text="Vanilla"},
new SelectListItem() { Value="2", Text="Chocolate"},
new SelectListItem() { Value="3", Text="Strawberry"}
}, "Value", "Text", "2");
SelectList should take a constructor that takes in the selectedValue:
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
object selectedValue
)
But this only sets the SelectedValue on the entire collection. The individual SelectListItems haven't been set as Selected
Do I need to iterate over them individually and set selected for each as in this question?
The Selected property is being set by the SelectList constructor. The image you have shown is for the items argument (i.e the collection of SelectListItem that you passing to the method), not the result of calling the method.
The constructor does not modify the collection passed to it, it creates a new IEnumerable<SelectListItem>, and if you inspect the value of var x, then you will see that the 2nd SelectListItem (the one with Value = "2") will have its Selected property set to true.
However, the purpose of the SelectListItem class is for use in one of the HtmlHelper methods that generates a <select> (DropDownList(), DropDownListFor(), ListBox() and ListBoxFor() methods) which accept an IEnumerable<SelectListItem> as either the 1st or 2nd argument.
Unless you specifically not binding to a model property (e.g. #Html.DropDownList("NotAModelProperty", Model.YourSelectList)), then setting the Selected property is ignored because the method sets the selected option based on the value of the property your binding to (refer How to set “selectedValue” in DropDownListFor Html helper for more detail), therefore creating a new IEnumerable<SelectListItem> from the first one by using new SelectList(...) is pointless extra overhead.
The reason for using the SelectList constructor is to create an IEnumerable<SelectListItem> from an existing collection of objects, for example
IEnumerable<SelectListItem> options = new SelectList(db.Flavors, "ID", "Name")
which would get the records from the Flavors table, and set the Value based on its ID property, and the Text based on its Name property. It just provides an alternative to using (say)
IEnumerable<SelectListItem> options = db.Flavors.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Name
});

Why is my SelectList populating with an unwanted blank option selected

I am working to create a view that contains a dropdownlist. To generate the select list items, I wrote a method to return the list of SelectListItem desired for this dropdown - one of which has an attribute of Selected set to true.
I have traced through the method generating the IEnumerable<SelectListItem> representative of the options I wish to render, and it is returning the desired result.
However when I use Html.DropDownList() utilizing the IEnumerable<SelectListItem> returned above, my rendered select element
has an initial blank option which does not appear in the DOM. Selecting any option will remove it, but I am confused as to why
the selected option from the List<SelectListItem> is not honored.
Static method generating list of SelectListItem:
public static IEnumerable<SelectListItem> GetDropDownValues()
{
IEnumerable<MyClass> myClassesForList = MyClass.GetItemsForList();
List<SelectListItem> retVal = new List<SelectListItem>();
retVal.Add(new SelectListItem() { Text = "Choose", Value = "0", Selected=true });
IEnumerable<SelectListItem> myClassesSelectListItems =
from x in myClassesForList
select new SelectListItem
{
Text = x.Name,
Value = x.Value
};
return retVal.Concat(myClassesSelectListItems);
}
Pertinent Razor snippet:
#Html.DropDownList("dropDownVals", GetDropDownValues())
Edit 1: Screenshot of resulting drop-down list
Make sure there's not a viewbag/viewdata named dropDownVals, which holds a value that doesn't exist in the list returned by the method GetDropDownValues
What if you use AddRange instead of Concat:
retVal.Add(new SelectListItem() { Text = "Choose", Value = "0", Selected=true });
var myClassesSelectListItems = from x in myClassesForList
select new SelectListItem
{
Text = x.Name,
Value = x.Value
};
retVal.AddRange(myClassesSelectListItems);
return retVal;

need to combine to lists in a view

the two lists to be passed to the view from controller.
ViewBag.mylist1 = new Accounts().List(Category.Income);
ViewBag.mylist2 = new Accounts().List(Category.Expenditure);
HOw to combine thse two lists in a single view?
myList1 = myList1.Concat(myList2).ToList();
Concat returns an IEnumerable that is the two lists put together, it doesn't modify either existing list. Also, since it returns an IEnumerable, if you want to assign it to a variable that is List, you'll have to call ToList() on the IEnumerable that is returned.
You can use also AddRange()
ViewBag.myList1 = ViewBag.myList1.AddRange(ViewBag.myList2);
AddRange() modifies the list by adding the other items to it.
Concat() returns a new sequence containing the list and the other items, without modifying the list.
List<SelectListItem> lstFuelType = new List<SelectListItem>();
var FuelType = dbContext.APPL_COMMON_MST.AsNoTracking().AsQueryable().Where(cm);
lstFuelType = new SelectList(FuelType, "KEY", "VALUE").ToList();
lstFuelType.Insert(0,new SelectListItem { Text = "ALL", Value = "ALL", Selected = false });
ViewBag.FuelType = lstFuelType;

How to remove an object from a list collection?

I had to change on my lines of code around. I before had something like this
// this is in a static method.
List<string> mySTring = new List<string>();
mySTring.add("one");
mySTring.add("two");
However on one of my pages I have a dropdownlist that does not require the field "two" so instead of writing duplicate code all I did was
myString.remove("two");
Now I need to change my list to a List<SelectListItem> myList = new List<SelectListItem>();
So I have it now looking like this:
List<SelectListItem> myList = new List<SelectListItem>()
{
new SelectListItem() { Text = "one", Value = "one"},
new SelectListItem() { Text = "two", Value = "two"},
};
So now how do I remove the selectListItem that contains "two"? I know I probably could use remove by index. But I might add to list in the future so I don't want to start hunting down and changing it if the index changes.
Thanks
List<T> is, by default, going to be comparing object references (unless SelectListItem implements a custom equality method). So unless you still have a reference to the second item around, you are going to have to get it either by reference, or by finding the desired item:
var item = myList.First(x=>x.Value == "two");
myList.Remove(item);
Index may be easier...
You could use the RemovalAll method:
myList.RemoveAll(i => i.Text == "two");
Obviously this will get rid of all the items whose "Text" property is "two", but since you're using it in a ComboBox I'm assuming you'll only have one item for each "Text" value.
we can make mouse selection over the autocomplete div by adding this following code
into the jquery autocomplete function
here i have used the id name as Requiredid
$("#Requiredid").autocomplete({focus:function(e,ui) {
document.getElementById('Requiredid').value = ui.item.label;
document.getElementById('hdnValue').value = ui.item.id;//If You need this value you //can add this line
}});

Categories