get specific value from ArrayList in C# - c#

I am using ArrayList in Asp.net I want to extract specific items . My code is
ArrayList items = (ArrayList)Session["mycart"];
foreach(var v in items)
{
}
but this is not working . I want to get value like
v.myvalue;
My arralist is filled with several items coming from prevoius page.

The issue is that ArrayList stores all elements as object. You need to perform a cast to the type of object that contains myvalue.
For example
ArrayList items = (ArrayList)Session["mycart"];
foreach(var v in items)
{
MyObject o = v as MyObject;
if (o != null)
{
// do stuff with o.myvalue
}
}
It may be better to just use the generic List class rather ArrayList, although you may have a perfectly reason for doing otherwise. Generally, you should use the generic (e.g. List<MyObject>), not only for performance but also ease of use.

Related

How to Get Value in Result View C#?

I want to get value in my object. When I look my inside of object, I can see my value in Result View IEnumerable. But, I can't get this values.
When I write "value."; just see "ToString, GetType, GetHashCode and Equals". I try GetType and get value but I can't. Because, I haven't name of values. How solve we this problem?
The IEnumerable uses syntactic sugar in the background. IEnumerable I feels like a list but behaves differently. The bigest different is that IEnumerable is lazy evaulated. This means only the requested object will be loaded into the memory. The interface hase a CurrentItem property that is accessed by foreach loop.
Here are some options to access the underlaying value:
User foreach
foreach (var value in myEnumerableCollection)
{
Console.WriteLine(value);
}
Use LINQ
var value = myEnumerableCollection.FirstOrDefault(x => x == someSearchTerm);
Cast the enumartion to a list and use the list methods and use indexers or other list methods to grab the value. A small warning, this will force the collection load every element into the memory. If it is large this may cause some issues. For example loading x million rows of db table with no pagination.
int index = 1;
var value = myEnumerableCollection.ToList()[index];
You can cast your value to IEnumerable T, where T - is your type, for example:
if (value is IEnumerable<int> resultList)
{
foreach (int item in resultList)
{
Console.WriteLine(item);
}
};

How to get the value of a variable to a string?

I am trying to add a item to my listView. The listView populates but I am getting this:
Systems.Collection.Generic.List'1[System.String]
This is the code I am trying to use:
foreach (SearchResult entry in result)
{
var members = GetGroupMemberList(entry.GetDirectoryEntry());
var item = members;
itmListItem = new ListViewItem((string)entry.Properties["sAMAccountName"][0]);
itmListItem.SubItems.Add(item.ToString());
lvwListView.Items.Add(itmListItem);
lvwListView.Refresh();
itmListItem = null;
}
Thanks
The problem you're running into is that item is not a string: it's a List<string>, so calling ToString() on it doesn't show you anything more meaningful than its type. Often people really want to get something like a comma-separated list of items to show, which could be accomplished by saying string.Join(", ", members).
But I'm reading the tea leaves here and thinking you probably really want each item in the members to show up as a sub-item in your list, which you could accomplish like this:
foreach (SearchResult entry in result)
{
var members = GetGroupMemberList(entry.GetDirectoryEntry());
foreach(var item in members)
{
var itmListItem = new ListViewItem((string)entry.Properties["sAMAccountName"][0]);
itmListItem.SubItems.Add(item.ToString());
lvwListView.Items.Add(itmListItem);
}
lvwListView.Refresh();
}
Note that I'm declaring itmListItem closer to where you actually use it, which makes it unnecessary to set it to null later. It's generally good practice to declare variables closer to their usage, and in as small as scope as possible.

Linq anonymous properties over parameter

Is it possible select an anonymous type via list of properties as parameter. The method should look like:
public void TestLinq(List<"Properties"> properties, List<Data> data)
{
var dat = from d in data select new { properties };
}
I know the description sounds clumsy but I hope I get some help.
It would be important to know the term I have to look for this topic.
You can use the Dynamic LINQ query library (download the sample) to create the list of properties in your projection, like so:
public dynamic TestLinq(IEnumerable<Data> data, IEnumerable<string> properties)
{
// Validate parameters.
if (properties == null) throw new ArgumentNullException("properties");
if (data == null) throw new ArgumentNullException("data");
// Construct the field list.
var fields = new StringBuilder();
foreach (string p in properties) fields.AppendFormat("{0},", property);
// Throw an exception if there are no items.
if (fields.Length == 0) throw new ArgumentException(
"The properties enumeration contains no elements.", "properties");
// Remove the last comma.
fields.Length--;
// Select the items and return. Create the
// projection here.
return data.Select("new(" + fields + ")");
}
Note that the return type is of type dynamic, so you'll have no compile-time checking, and unless you're duck-typing, you probably won't have much knowledge of the fields.
You might be better off creating strong types for this, depending on your needs (if this is based on user-input, then you can't obviously).
Here you go, this is based on this answer https://stackoverflow.com/a/5310828/491950
List<string> properties = new List<string>() { {"ResultPrefix"}, {"ProfileResult"}};
foreach (dynamic d in ListProperties(properties, cellValues))
{
Console.WriteLine(d.ResultPrefix);
}
public static List<dynamic> ListProperties(List<string> properties, List<ChemistryResult> chemistryResults)
{
List<dynamic> output = new List<dynamic>();
foreach (ChemistryResult chemistryResult in chemistryResults)
{
IDictionary<string, Object> result = new ExpandoObject();
foreach (string property in properties)
{
PropertyInfo propertyInfo = typeof(ChemistryResult).GetProperty(property);
result[property] = propertyInfo.GetValue(chemistryResult);
}
output.Add(result);
}
return output;
}
You cannot use anonymous types in a method signature. It cannot be used as a parameter or the return type.
What you could do, is declare the parameter as dynamic, but dynamic can get really sticky, so I recommend avoiding it. You could have a List<dynamic> parameter, then you will be able to access members of the type, but you will not get type checking at compile time.
Another option it to use IEnumerable or IList. Using either of these will allow you to access the members of the collection without knowing the type. This is safer, as you have all of your compile time checks, but will not allow you to access members or the anonymous type.
But really, you should just convert your anonymous type into a real class so you can make your life easier.
I am sorry for the confusion. The outcome should be a csv that's right. The user should be able to define the order of the columns. But for me it was very difficult to formulate a good question. I am looking for a solution with expresisons not with reflection. My Idea was to generate a List of anonymous objects (with the right order) and out of them I wanted to create the csv. So I know the following is working:
public void Get(List<Value> data,Expression<Func<Value, T>> converter)
{
var dat = from d in data
select
new
{
converter
};
}
Is it possible to safe the Expression> converter in a property and combine many of them to one? So I would get the corret order

C# object to array

Using reflection I have an object which I need to cast into an iterable list of items (type unknown, will be object). Using the Watch window I can see my object is an array of some type as it tells me the number of elements and I can explode the tree view to see the elements themselves.
Firstly, I need to check that the object passed is some kind of array (might be List, might be object[], etc). Then I need to iterate through that array. However, I can't do the type conversion.
Here's how I'm using it (abbreviated):
private static void Example(object instance, PropertyInfo propInfo)
{
object anArray = propInfo.GetValue(instance, null);
ArrayList myList = anArray as ArrayList;
foreach (object element in myList)
{
// etc
}
}
I've tried various different casts. The above doesn't raise an exception but mylist is null when anArray actually exists and contains items. The actual instance being saved is a strongly-typed List<> but could take a limited subset of forms if necessary. But the point of the exercise is that this Example() method doesn't know the basic type of the property.
Casting it to an ArrayList is only going to work if the object actually is an ArrayList. It wont work with a System.Array, or a System.Collections.Generic.List`1 for example.
I think what you actually should do is cast it to IEnumerable, since that is your only requirement to loop over it...
object anArray = propInfo.GetValue(instance, null);
IEnumerable enumerable = anArray as IEnumerable;
if (enumerable != null)
{
foreach(object element in enumerable)
{
// etc...
}
}
Try to cast to IEnumerable. This is the most basic interface all enumerables, arrays, lists etc. implement.
IEnumerable myList = anArray as IEnumerable;
if (myList != null)
{
foreach (object element in myList)
{
// ... do something
}
}
else
{
// it's not an array, list, ...
}
Simply Try This
string[] arr = ((IEnumerable)yourOjbect).Cast<object>()
.Select(x => x.ToString())
.ToArray();
Try this:
var myList = anArray as IEnumerable;
if (mylist != null)
{
foreach (var element in myList)
{
// etc
}
}
You might also need to specify the generic type of the IEnumerable, depending on your situation.
You should be able to cast it to IEnumerable if it is a collection of any sorts (array, list, etc.). Also PropertyInfo contains a PropertyType property which you could use to find out the actual type if you wanted to.
Just in My case I need to define data type IEnumerable<string>
var myList = anArray as IEnumerable<string>;

How to create a List<unknown type at compile time> and copy items via System.Reflection.PropertyInfo

I have come across something pretty complex. I would be obliged if anyone can help.
1) I have to create a List<> of unknown type at compile time. That I have already achieved.
Type customList = typeof(List<>).MakeGenericType(tempType);
object objectList = (List<object>)Activator.CreateInstance(customList);
"temptype" is the custom type thats been already fetched.
2) Now I have PropertyInfo object which is that list from which I have to copy all items to the the instance that I have just created "objectList"
3) Then I need to iterate and access the items of "objectList" as if it were a "System.Generic.List".
Cutting long story short, using reflection I need to extract a property that is a list and have it as an instance for further use. Your suggestions would be appreciated. Thanks in Advance.
Umair
Many of the .NET generic collection classes also implement their non-generic interfaces. I'd make use of these to write your code.
// Create a List<> of unknown type at compile time.
Type customList = typeof(List<>).MakeGenericType(tempType);
IList objectList = (IList)Activator.CreateInstance(customList);
// Copy items from a PropertyInfo list to the object just created
object o = objectThatContainsListToCopyFrom;
PropertyInfo p = o.GetType().GetProperty("PropertyName");
IEnumerable copyFrom = p.GetValue(o, null);
foreach(object item in copyFrom) objectList.Add(item); // Will throw exceptions if the types don't match.
// Iterate and access the items of "objectList"
// (objectList declared above as non-generic IEnumerable)
foreach(object item in objectList) { Debug.WriteLine(item.ToString()); }
Do you think this would help you? Efficient way of updating a collection from another collection
I came up with something similar. I borrowed the SetProperties() method from NullSkull and wrote a simple method that calls the NullSkull SetProperties():
public static List<U> CopyList<T, U>(List<T> fromList, List<U> toList)
{
PropertyInfo[] fromFields = typeof(T).GetProperties();
PropertyInfo[] toFields = typeof(U).GetProperties();
fromList.ForEach(fromobj =>
{
var obj = Activator.CreateInstance(typeof(U));
Util.SetProperties(fromFields, toFields, fromobj, obj);
toList.Add((U)obj);
});
return toList;
}
...so with one line of code I can retrieve a List<desired class> populated with matching values by name from List<source class> as follows:
List<desired class> des = CopyList(source_list, new List<desired class>());
As far as performance goes, I didn't test it, as my requirements call for small lists.

Categories

Resources