I am using the following code in C#. I am adding the values into the arraylist by using index. Now I want to read the values from the arraylist by using the index only. In the following example I am simply reading all the values from the arrylist but I want to read the values from the arrylist based on index( for e.g Customer_Details[i]) for each element at index i.
public struct Cust_Info
{
public String Client_Key;
public String Registration_Key;
public int Standard;
public Cust_Info(String C_Key, String Reg_Key, int Std)
{
Client_Key = C_Key;
Registration_Key = Reg_Key;
Standard = Std;
}
}
private void Form1_Load(object sender, EventArgs e)
{
ArrayList Customer_Details = new ArrayList();
for (int i = 0; i < 1; i++)
{
Customer_Details.Insert(i, new Cust_Info("A", "B", 1));
}
//for (int i = 0; i < 1; i++)
//{
Customer_Details.Insert(1, new Cust_Info("C", "D", 2));
for (int i = 0; i < 1; i++)
{
ArrayList obj=new ArrayList();
//((ArrayListOFStructures.Form1.Cust_Info)((new System.Collections.ArrayList.ArrayListDebugView(Customer_Details)).Items[0])).Client_Key
//obj = (ArrayList)Customer_Details[i];
foreach (Cust_Info temp in Customer_Details)
{
//comboBox1.Items.Add(Customer_Details[0].ToString());
comboBox1.Items.Add(temp.Client_Key);
comboBox1.Items.Add(temp.Registration_Key);
comboBox1.Items.Add(temp.Standard);
}
}
}
In the above code i want to make the use the structure only. How can I read the values from the arrylist based on index. Can you please provide me any code or link through which I can resolve the above issue ?
I'm confused; you can get an item out of an ArrayList by index simply by:
Cust_Info cust = (CustInfo)theList[index];
However, ArrayList is pretty rare in anything >= .NET 2.0, a List<Cust_Info> would make this much easier. Also, Cust_Info looks to me very much like it should be a class (it is very rare to write a struct in .NET, and usually to denote "values" - a customer isn't a "value"). And public fields are also very much discouraged.
Note that currently you are (because it is a struct) actually copying the Cust_Info whenever you fetch it from (or place it in) the list; that isn't necessarily what you intend...
You can try something like
ArrayList arr = new ArrayList();
for (int iIndex = 0; iIndex < arr.Count; iIndex++)
{
object o = arr[iIndex];
}
But I would rather go with
List Class and List.Count Property
for(int i=0; i<Customer_Details.Count/*or.Length*/; i++)
Customer_Details[i] = something;
Related
I would like to store reference of an ushort variable in an ushort array, so that the value of the variable changes when I change the values inside the ushort array. Here is my sample code which will give a clear picture of what I'm trying to achieve.
public void IndexSetter(List<int> indexVal,Rootobject objectVal)
{
ushort[] refereneArray = new ushort[8]
{
objectVal.index1, objectVal.index2,
objectVal.index3 , objectVal.index4,
objectVal.index5, objectVal.index6,
objectVal.index7, objectVal.index8
};
for(int j = 0; j< indexVal.Count;j++)
{
refereneArray[j] =(ushort) indexVal[j];
}
}
Instead of storing the values like from above code , I need to store the reference so that the changes in indexVal list reflect in the values of index1, index2.. etc
I´d suggest not to have 8 indexes with the exact same name (except a number). Give every member of your class a name describing what it´s ment to be, however index6 isn´t really self-explanatory.
Having said this what you can do is to have one array of indexes within your class itself:
class Rootobject
{
public int[] Indexes { get; set; }
}
Now you can access them as follows:
public void IndexSetter(List<int> indexVal, Rootobject objectVal)
{
for(int i = 0; i < indexVal.Count; i++)
objectVal.Indexes[index] = indexVal[i];
}
Or even shorter:
objectVal.Indexes = indexVal.Cast<ushort>().ToArray();
You can do it with unsafe code, using array of pointers like this:
static unsafe void IndexSetter(IList<ushort> indexVal, Rootobject objectVal) {
fixed (ushort* r1 = &objectVal.index1)
fixed (ushort* r2 = &objectVal.index2) {
ushort*[] refereneArray = {r1, r2};
for (int j = 0; j < indexVal.Count; j++) {
*refereneArray[j] = (ushort) indexVal[j];
}
}
}
Should you really do this in real application is another story. There is very high chance that there is a better way to solve your problem, but you didn't tell us what the actual problem is.
If perfomance is not critical - you can use reflection:
static void IndexSetter2(IList<ushort> indexVal, Rootobject objectVal) {
int i = 0;
foreach (var field in objectVal.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
.Where(c => c.Name.StartsWith("index") && c.FieldType == typeof(ushort))
.OrderBy(c => c.Name)) {
field.SetValue(objectVal, indexVal[i]);
i++;
}
}
I have to remove duplicate rows in a array using id using C#. In the array I have 3 columns.
Following is my code
[WebMethod]
public static string GetYesterdayPatientsByTime()
{
try
{
BusinessLogicLayer bal = new BusinessLogicLayer();
DataSet ds = bal.GetYesterdayPatientsByTimeBAL();
string[] output = new string[(ds.Tables[0].Rows.Count * ds.Tables[0].Columns.Count)];
int count = 0;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
output[count++] = ds.Tables[0].Rows[i].ItemArray[j].ToString();
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
js.MaxJsonLength = 2147483644;
return js.Serialize(output.Distinct().ToArray());
}
catch (Exception)
{
return "";
throw;
}
}
You can expand the Distinct() method into DistinctBy(), which will allow You to distinct by several columns - check link: LINQ's Distinct() on a particular property
Another solution that came in my mind is create ArrayList with the results. While going through whole array, You will check if the element does exist in list, and if not You will add it.
After checking MSDN - https://msdn.microsoft.com/cs-cz/library/bb348436(v=vs.110).aspx - You can find that Distinct() by default using Default IEquatable, so You can also add own Comparer to the class, which will compare based on ID.
I have an array List as follows;
ArrayList myArrayList = new ArrayList();
for (int i = 0; i <= 1000; i++)
{
myArrayList.Add(i.ToString());
}
Then I am using IEnumerator and trying to pass the value to a function.
IEnumerator eee = myArrayList.GetEnumerator();
Now calling the function.
iteratefrom5to10(eee); //The error shown here is some invalid arguments.
static void iteratefrom5to10(IEnumerator<int> ien)
{
while (ien.MoveNext())
{
MessageBox.Show(ien.Current.ToString());
}
}
The above approach has worked with List. But not with ArrayList. What is wrong?
Stop using ArrayList - there are very few cases where you'd want to use it.
Since you're working with a list of integers, just use List<int> instead - no need to convert all the values to string and back :)
Finally, why are you using GetEnumerator anyway? Change the argument to IEnumerable<int> and the while to a foreach:
var list = new List<int>();
for (var i = 0; i <= 1000; i++)
{
list.Add(i);
}
static void iteratefrom5to10(IEnumerable<int> ien)
{
foreach (var value in ien)
{
MessageBox.Show(value.ToString());
}
}
IEnumerables are very easy to work with. For example, as your method's name suggests you want to iterate from 5 to 10, the same can be done with a simple list.Skip(4).Take(6).
You can do:
myArrayList.ToArray().AsEnumerable();
You need to cast myArrayList to IEnumerable<int> like this:
IEnumerator<int> eee = myArrayList.Cast<int>().GetEnumerator();
Please note that you are adding strings to the ArrayList. You should be adding integers instead like this:
ArrayList myArrayList = new ArrayList();
for (int i = 0; i <= 1000; i++)
{
myArrayList.Add(i);
}
I am creating an application in window application using c#. I have a string array,and its value will be updated in each timer tick event. later on ,i have to convert this array into object array. I know, if we are modifying string many times,it can be time consuming to create new string objects.so i want to use stringBuilder.
let say, in timer tick event:
for (int i = 0; i < 10; i++)
{
n[i] = i.ToString();
}
where n is the string array and i want to use stringbuilder instead of array.
is it possible? how do i do this? how do i convert stringBuilder type to object type?
You do not need a StringBuilder here. A StringBuilder is only called for when processing (usually: concatenating) a single string many times. You have many small and unrelated strings.
What you probably want is to replace the array string[] with a List<string>.
You can keep your array of strings and use a StringBuilder in the loop.
var myValues = new String[100];
void tick() {
var sb = new StringBuilder();
for (int i = 0; i < 10; i++){
sb.append(i.ToString());
}
myValues.add(sb.ToString());
}
This adds all values in the range of 0 to 10 to one string. I don't know why you'd need this, so if you want to do something different you should clarify.
You can do something like this
StringBuilder obj=new StringBuilder();
for (int i = 0; i < 10; i++)
{
obj.append(i.ToString());
}
Here is another approach that does not need to use an array or StringBuilder and which should be efficient enough if the sequence is not too large:
string nums = String.Join("", Enumerable.Range(0, 10));
However, string.Join is really efficient if the input is already an array. In this case it might really be more efficient to use a StringBuilder:
string nums = Enumerable.Range(0, 10)
.Aggregate(new StringBuilder(), (a, b) => a.Append(b))
.ToString();
I would suggest you to use code something like :
class Program
{
static void Main(string[] args)
{
var dic = new Dictionary<int, StringBuilder>();
//Initialize dictionary
for (int i = 0; i < 10; i++)
{
dic.Add(i, new StringBuilder());
}
TimerElapsed(dic);
TimerElapsed(dic);
Process(dic.Values.ToArray());
}
public static void Process(object[] objects)
{
//Do your processing
}
public static void TimerElapsed(IDictionary<int, StringBuilder> dic)
{
for (int i = 0; i < 10; i++)
{
dic[i].Append(i.ToString());
}
}
}
Such code will give you benefits of collection and flexibility (for eg: you could convert to array easily)
I have list of structure. I want to modify a particular data from the structure.
And the structure is at the particular index location of the List.
I want to do something like this:
struct sample
{
int a;
string name;
}
List<sample> list = new List<sample>();
for(int i=0; i < list.Count; i++)
{
list[i].a = someotherlist[i].data;
}
The problem is that the list indexer creates a copy of the struct, i.e. it is really:
for(int i=0; i < list.Count; i++)
{
var completelyIsolatedClone = list[i];
completelyIsolatedClone.a = someotherlist[i].data;
}
The compiler is preventing you making an obvious mistake. The code you have uses the get, mutates a separate copy of the data, but never puts it back - so your change doesn't do anything useful. Note that the Mono folks think it would be nice if it worked your way, though: http://tirania.org/blog/archive/2012/Apr-11.html
Note that an array works differently; with an array you are touching the struct in place, so the following would work fine:
for(int i=0; i < list.Count; i++)
{
someArray[i].a = someotherlist[i].data;
}
Another approach is to copy the data out (the get accessor), mutate it, and put it back:
for(int i=0; i < list.Count; i++)
{
var completelyIsolatedClone = list[i];
completelyIsolatedClone.a = someotherlist[i].data;
list[i] = completelyIsolatedClone;
}
or better, acoid mutable structs completely, perhaps with a method that applies the change to a new copy:
for(int i=0; i < list.Count; i++)
{
list[i] = list[i].SetA(someotherlist[i].data);
}
where SetA creates a new struct, like DateTime.AddDays etc, i.e.
public SomeType SetA(int a) {
return new SomeType(this.X, this.Y, a, this.Z);
}
The reason you can't do it is because Sample is a struct, if you change it to a class then you can modify it. Structures are passed by value, that is, when a structure is returned by a method, a copy of the structure is returned, not the orginal structure. So when list[i].a = someotherlist[i].data; is run, you are actually modifying the copy and the orginal structure is not being changed. The compilers prevents you from doing this as it is probably not what you had intended.
You may look at this thread Why couldnot I modify the value of item from Generic Collections) ?
I just modified my code as bellow and it works fine for me
public struct test
{
public int data;
public string name;
public int port_index;
}
static void Main(string[] args)
{
List<test> look_up = new List<test>();
test obj;
obj.data = 1;
obj.port_index = 0;
obj.name = "aaaa";
look_up.Add(obj);
test obj1;
obj1.data=3;
obj1.port_index=1;
obj1.name="sssss";
look_up.Add(obj1);
for(int i=0;i<look_up.Count;i++)
{
if (i == 1)
{
test temp = look_up[i];
temp.data = 5;
look_up[i] = temp;
}
}
}