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
Related
I have a two class properdata and pprosecnddata both classes having property
I want to access product property from properdata class list object. How is it possible,below is my sample code
pupilc class ProperData
{
public string code{get;set;}
public List<ProSecndData>Secnd{get;set;}
}
public class ProSecndData
{
public string product{get;set;}
}
I am trying to call property like that
class Program
{
static void Main(string[] args)
{
ProperData.Secnd.Product = "Hello";
}
}
you cannot directly access property of Secnd as it is a list
you need to iterate or select the index of the List<Secnd>
you must initialize Secnd first and Secnd should have items in the list
properData.Secnd = new List<ProSecndData>();
so it can be access via
foreach(var second in properData.Secnd)
{
second.product = "hello";
}
//or
for(var i = 0; i < proderData.Secnd.Count(); i++)
{
properData.Secnd[i].product = "hello";
}
//or
var index = //0-length of list;
properData.Secnd[index].product = "hello";
if you want to have items first then add first on your Secnd List
properData.Secnd = new List<ProSecndData>();
properData.Secnd.Add(new ProSecndData{ product = "hello"});
then you now can iterate the list by using methods above
You are trying to access list as a single object, which is not possible.
you need to create single instance of your list class and then you can add string in that single instance.
properData.Secnd = new List<ProSecndData>();
ProSecndData proSecndData = new ProSecndData();
proSecndData.product = "Hello";
properData.Secnd.Add(proSecndData);
Actually I know the answer already, you have not created a constructor to initialise your List.
I'm guessing you get a object null ref error?
Create the constructor to initialise your list and it should be fine.
But in future, please post the error message (not the whole stack, just the actual error) as well as all the code required to repeat the issue. Otherwise you run the risk of getting your question deleted
(It should be deleted anyway because it could be considered a "what is a null ref err?" question).
Also you are accessing an item in a list like the list is that item (should be more like: ProperData.Secnd.elementAt(0).product, please also note the capitalisation of 'product' in the model vs your code.
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);
}
}
}
}
How is it possible to find a specific object from a list?
Lets say i have a function that takes an object and a list that contains objects of this type and returns the number at which position the specific object is found.
The only way i could think of a solution is to run the list through with a foreach loop, but isn't there a better way?
Thanks
You can use the IndexOf(T item) method:
myList.IndexOf(myItem);
It returns the index of the first occurrence of the item.
The only way i could think of a solution is to run the list through with a foreach loop
Generally, you need a loop (a for or foreach) to find an object in a list. You could use it directly, or through a function that iterates over list elements, but there is going to be a loop. There is no way around it: unless you know something special about the way the elements of the array are arranged, you have to look at them all.
One case of knowing something special about arrangement of elements is knowing that an array is sorted. If this is the case, and when you know the value of the attribute on which the element is sorted, you can find the element much faster by using binary search.
You could use linq expressions
List.where(condition)
Or
List.Select(condition).FirstOrDefault
Based on search condition it will return the item you want.
You can use method IndexOf or if you use a special condition then you can use method
public int FindIndex(Predicate<T> match);
where match is delegate
public delegate bool Predicate<T>(T obj);
In fact it is similar to standard C++ algorithm std::find_if
To see whether object is there You might just need List<T>.Contains method
It states,
Determines whether an element is in the List.
And you need to use it like List<T>.Contains(T type item) , where T is the same type of List and item you need to compare. In your case it's a the type of Object
And to return the index you can use List<T>.IndexOf Method
Searches for the specified object and returns the zero-based index of the first occurrence within the entire List.
Simple Console program
class Program
{
static void Main(string[] args)
{
MyType a = new MyType() { id = 10 };
MyType b = new MyType() { id = 20 };
MyType c = new MyType() { id = 30 };
List<MyType> testList = new List<MyType>();
testList.Add(a);
testList.Add(b);
Console.WriteLine(testList.Contains(a)); // <= Will return true
Console.WriteLine(testList.Contains(c)); // <= Will return false
Console.WriteLine(testList.IndexOf(a)); // <= will return 0 : the index of object a
Console.ReadKey();
}
}
// A simple class
class MyType
{
private int ID;
public int id
{
get { return ID; }
set { ID = value; }
}
}
I am creating an array of string[] in my c# program to save location ("name","Position") of a bunch of elements. The problem is any time I had to introduce a new element I have to change the code at several places according to index of elements:
string[] list = new string[4];
list[0] = "[ELEMENT #1 NAME],[ELEMENT #1POSITION]";
list[1] = "[ELEMENT #2 NAME],[ELEMENT #2POSITION]";
list[2] = "[ELEMENT #3 NAME],[ELEMENT #3POSITION]";
list[3] = "[ELEMENT #4 NAME],[ELEMENT #4POSITION]";
What I am looking for is something like an dynamic array so that I do not have to change the index location every time I introduce/ remove an element from list.
You can use List<string> as a dynamic array, it supports IEnumerable<string> for enumerating, or you can call LINQ and ToArray().
For example:
var list = new List<string>();
list.Add("[ELEMENT #1 NAME],[ELEMENT #1POSITION]");
string array[] = list.ToArray();
However, I'd actually recommend a dictionary in this case and not a list, a dictionary will let you store key-value pairs.
For example:
var dict = new Dictionary<string,int>();
dict["Element #1 Name"] = #Element #1 Position#;
Note that I've no real idea what type the position is, could be an int, a string or even a Point, but you get the idea.
You then don't need to bother with indices but refer to everything by name:
var el1_pos = dict["Element #1 Name"];
var el999_pos = dict["Element #999 Name"];
You can use List<T> if you want a dynamically sized collection and don't bother with the index. And you should also create a type with two properties (Name and Position) and have a list of that type instead of storing them as string. It's easier to maintain, you don't have to parse the string every time you wanna get/set the Name or Position of a particular object.
Normally, you would just use a List<String> here. The Add method allows you to just add an element, no indexing required.
List<string> list = new List<string>();
list.Add("Test");
In your case, since you have "Name" and "Position" associated with each other, consider using a List<PositionedThing> (a custom class in other words) or a Dictionary<String, String> to store your mappings.
The class would look like:
public class PositionedThing
{
public String Name {get; set;}
public String Position {get; set;}
}
Try
List<string> list = new List<string>();
list.Add("[ELEMENT #1 NAME],[ELEMENT #1POSITION]")
Unless I've misunderstood your question that should be what you want
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();