I have a ListBox with Integers in it that gets them from a SQL database. Now I wanted to put these elements into a List when they get selected but somehow it won't work. Here is the code:
List<Int32>typeElements = new List<Int32>();
if(form1.listBox.SelectedIndex != -1)
{
foreach (var selectedItem in form1.listBox.SelectedItems)
{
typeElements.Add(selectedItem);
}
}
He tells me he can't convert object to int and that the method has some invalid arguments. How to handle that?
ListBox.SelectedItems is a collection of objects. You can't simply take an element from this collection and add it to a typed list of integers.
You need a conversion
typeElements.Add(Convert.ToInt32(selectedItem));
If you want to use Linq and the IEnumerable extensions then you could write your loop in one line
// List<Int32>typeElements = new List<Int32>();
List<Int32> typeElements = form1.listBox.Items.Cast<int>().ToList();
EDIT:
Following your comment then you need to extract the Integer element from the DataRowView
DataRow row = (selectedItem as DataRowView).Row;
typeElements.Add(row.Field<int>("NameOfYourDataBaseIntegerField"));
Try this (using System.Linq):
OfType() is an extension method, so you need to use System.Linq
List<Int32> selectedFields = new List<Int32>();
selectedFields.AddRange(listbox.CheckedItems.OfType<Int32>());
Or just do it in one line:
List<Int32> selectedFields = listbox.CheckedItems.OfType<Int32>().ToList();
Related
public class LIST
{
public double num;
public double longi;
public double ux;
public double vy;
}
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
L1.ux= // I take l1.ux from stream reader by reading a file and made this
for
L1.vy=.. the other parameters
L1.longi=..
L1.num=....
LIST1.Add(L1)
Here my problem is ı made a list that contains 4 parameters. But ı want to find just one parameter value for instance L1.num how can I take this value from a list?
var indexOfLISTObject = 1 //you need to know which object from LIST1 you want to use
var numParamOfLISTObject = LIST1[indexOfLISTObject].num;
Please Don't name your object LIST. It will create readability issues down the line for you. Name the object what a particular item in your list will represent.
To access a particular property from an item in list you can do following
List l1 = new list();
//Add items ...
//Print property from particular index
Console.WriteLine(l1[index].propertyname);
Put the paremeters inside a list one by one.
in your example you want the parameter num.
List parameterNum = new List();
parameterNum = l1.Select(x => x.Num).ToList();
parameterNum has now the list of Num from l1 list.
If you mean to find/search for a particular value, you could also use System.Linq. For example if you would like to find a member where num is set to 2, you could do this:
LIST1.Where(item=>item.num==2).FirstOrDefault()
According my Understanding If you want to Get objects that contain with specific parameter
then you can use this code
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
var SearchedValue= List1.where(x=>x.num==L1.num).tolist();
if you want just L1.num value then you can use this line (if searched record will 1 then you should use this)
var SearchedValue= List1.where(x=>x.num==L1.num).FirstOrDefault().num;
you can use
LIST1[index].propertyname //index is index of list element and propertyname is the name of property you want to access
I want to alter the items of a list, which they are lists too.
I tried:
for (int i = pChain.Count -1; i> 0; i --)
{
List<String> item = pChain[i];
item = item.RemoveSequentialRepeats().ToList();
}
Where the RemoveSequentialRepeats is a static function like:
public static IEnumerable<T> RemoveSequentialRepeats<T>(
this IEnumerable<T> source) ....
As I trace the code, the function changes the list and removes the consecutive repeated items, but it is not stored in the main list pChain. Do I do something wrong?
From your example, it appears the RemoveSequentialReapeats doesn't edit the list but creates a new one instead. So, you're assigning a new value to item, and pChain doesn't update and remains with the original list. What you should do is add the line
pChain[i] = item;
To fix the problem you've to assign back result from Linq statement to pChain.
pChain[i] = item;
Code can be even simplified and make it one liner code.
pChain = pChain.Select(li=> li.Select(item=>item.RemoveSequentialRepeats()).ToList());
Can anyone tell when to use Add() and AddRange() of ArrayList?
If you want to add a large number of values at one time, use AddRange.
If you are only adding a single value or adding values infrequently, use Add
Difference Between Add and AddRange
Add---------It is used to add the item into the list one by one.
AddRange-----------It is used to add the bulk of list item into the another list.
List<string>list1=new List<string>();//using Add
List<string>list2=new List<string>();//using AddRange
list1.Add("Malathi");
list1.Add("Sandhiya");
list1.Add("Ramya");
list1.Add("Mithra");
list1.Add("Dharshini");
list2.AddRange(list1);
output:
//The output of list1 contains
Malathi,
Sandhiya,
Ramya,
Mithra,
Dharshini
//The output of list2 Contains
Malathi,
Sandhiya,
Ramya,
Mithra,
Dharshini
C# List class represents a collection of a type in C#. List.Add(), List.AddRange(), List.Insert(), and List.InsertRange() methods are used to add and insert items to a List.
AddRange - AddRange adds an entire collection of elements. It can replace tedious foreach-loops that repeatedly call Add on List.
public virtual void AddRange (System.Collections.ICollection c);
Add - Add method adds an object to the end of the List.
public virtual int Add (object value);
Example: Now set an array of elements to be added to the list.
// array of 4 elements
int[] arr = new int[4];
arr[0] = 500;
arr[1] = 600;
arr[2] = 700;
arr[3] = 800;
Use the AddRange() method add the entire collection of elements in the list −
List<int> list = new List<int>();
list.AddRange(arr);
But if you want to use List.Add() method,
List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);
For details, you can check Insert an Item into a C# List
If You want to add single variable in List, then Add() is used.
But if you want to add List or multiple variable in List, then AddRange() can be used
var t = (from t1 intable1
join t2 in table2 on t1.t1id equals t2.t2id
select new ABCViewModel
{
FirstName = t1.firstname,
LastName = t1.Lastname
})
.where(t2.age>35)
.ToList();
var s = (from t1 intable1
join t2 in table2 on t1.t1id equals t2.t2id
select new ABCViewModel
{
FirstName = t1.firstname,
LastName = t1.Lastname
})
.where(t2.age < 35)
.ToList();
t.AddRange(s);
return t;
It will add result of List s to List t along with result of List t.
Difference b/w Add() and AddRange() methods is very straight forward
Add() is used to add an element in the list.
AddRange() is used to add a range of elements(multiple elements) at once in the list.
Note: Multiple elements can be another entire Array, HashTable, SortedList, ArrayList, BitArray, Queue, and Stack.
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//create the first arraylist
ArrayList arraylist1 = new ArrayList();
arraylist1.Add(5);
arraylist1.Add(7);
//create the second arraylist
ArrayList arraylist2 = new ArrayList();
arraylist2.Add("Five");//add the single value at time to the arraylist
arraylist2.Add("Seven");//add the single value at time to the arraylist
//perform AddRange method
arraylist1.AddRange(arraylist2);//adding the arraylist as bulk in another arraylist
// Display the values.
foreach (object i in arraylist1)//iterating the arraylist1 value to object
{
Console.WriteLine(i);
}
}
}
}
There is a array list that contain generic lists. How can i access the variables that in generic list? But i want to access the variables via the array list.
ArrayList TheList = new ArrayList();
List<NewType>[] GenericLists = new List<NewType>[4];
GenericLists[0].Add(variable);
.
.
.
for (int i = 0; i < 4; i++)
{
TheList.Add(GenericLists[i]);
}
How can i print the variables via the Array list?
You need to iterate over the items of your ArrayList and cast each item to List<NewType> then you can iterate over the items in the lists and display them or whatever you want...
foreach(var list in TheList)
{
var currentList = (List<NewType>)list;
...
}
Or you can use Linq methods to cast them:
foreach(var list in TheList.Cast<NewList>())
These assumes that all items in the array list are of type NewList. Otherwise you will get an InvalidCastException at runtime. To avoid this you can use is or as operators to check if the type is NewList, or you can use OfType method which does this for you:
foreach(var list in TheList.OfType<NewList>())
List<object> li = new List <object>(Items);
string name = "";
foreach (var item in Items)
{
name = item["title"].ToString();
}
return name;
Using this code snippet, I can't find a way for to change the return to output all items from the list. As is, it only returns the last item. How can I get every item returned?
You have to return a new list, in your example you're just setting name to the current name then returning name at the end. Since you loop through all the elements name is set to the final value in the list before returning. Besides that, your return type is string unless you concatinate all the elements in li into a single string then you can't return a list as a string.
List<string> newList = li.Select(x => x["title"].ToString()).ToList();
Will create a new list of strings where each element is the title of an element from your source list, li.
If you really want to return a string you can use (I believe) String.Join or, (this one I'm certain of) Aggregate like so;
return li.Aggregate((c, n) => c["title"].ToString() + ", " + b["title"].ToString());
The above code will return string that is a comma separated list of the elements titles.
This is a little rediculous for just returning a list but it works. I would personally just return the whole thing at once.
List<object> li = new List <object>(Items);
string name = "";
foreach (var item in Items)
{
yield return item["title"].ToString();
}
As you know, method can returns one value with return statement. So you shoud to return all items as IEnumerable (List, Array, etc).
return Items.Select(x => x["Title"].ToString()).ToArray();
You need to return the whole List and extract each element when you want to use them. You cannot pass all these elements at once unless you store them in some sort of container (an array, for example.)
Again, this does not make much sense if you already have a List object to house them. The CLR's List<T> type is an adjustable length array, not the classic linked list.
If you can post more detail as to what your exact scenario is, we can help you better.