How to get the value of a variable to a string? - c#

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.

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);
}
};

get specific value from ArrayList in 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.

How to read an array of objects

I have a C# list of objects and I'm trying to access its nested object. Here's the structure from Visual Studio's debugger (sorry I can't embed images since I'm a newbie to the site):
>product.Product {Product.AxdEntity_Product_EcoResProduct[1]}
>> - [0] {Product.EcoResProductMaster} // #1 - Please note curley braces
>>> - [Product.EcoResProductMaster] // #2 - Please note brackes
>>> + base {Product....
>>> + ModelingPolicy
>> + Identifier
To access the properties in #1, I would do the following:
var prod = product.Product[0];
Then I can access "Identifier" as such:
var identifier = prod.Identifier[0]...
To access the properties in #2 (such as ModelingPolicy), I'm not sure how to go about it:
var prod = product.Product[0][WhatShouldGoHere?].ModelingPolicy[0] ...?? I need help here
Eventually, I'd like to access the ModelingPolicy[0] like I did with prod.Identifier[0].
The Product class is being returned from a web service and I don't have access to its definition. At least I don't think I do.
Thank you for any guidance!
Looks to me like:
var ecoResProductMaster = product.Product[0].EcoResProductMaster; // Product type
var modelingPolicy = ecoResProductMaster.ModelingPolicy;
Have you tried this?
var productList = product.ToList()
foreach(var prod in productList)
{
var identifier = prod.identifier
foreach (var modelingPolicy in identifier.ModelingPolicy)
{
//do somthing with modeling policy
}
//do more stuff with product
}
As an aside please sort your naming conventions out. Having an array called product that contains a number of Product objects is just confusing
It's difficult to tell what you're going for here. Is this a List or array?
If it is a list then you can just foreach through the list to access each object.
Like if you have
List<SomeObject> someObjectList = new List<SomeObject>();
Then after you add a bunch of SomeObjects to the List you can just access the SomeObjects in a foreach loop.
foreach (SomeObject s in someObjectList)
{
// then to access nested objects
var n = s.SomeNestedObject;
// do something with n
}
Thanks all for your input. The answer from SmartDev helped me access the objects in the inner array. To do this, simply do the following:
var productMaster = (EcoResProductMaster)product.Product[0];
var modelingPolicy = productMaster.ModelingPolicy[0];
Of course, this is assuming that only one object is returned in the array, hence "[0]" but this should eventually go inside a foreach loop.
What I learned was if an object is returned without an index such as //#2 as noted above, a type cast should allow me to access it. However, if an index is returned such as //#1, then using [0] will allow me to access its properties.

IEnumerable<> being skipped by foreach code; Converting IEnumerable<> to List<> doesnt return anything

Basically I have this code:
public static async Task<bool> SubmitOrdertoBroker(CASOrderModel order, IEnumerable<CASOrderItemModel> modelOrderItems)
{
ObservableCollection<CASOrderItem> casOrderItemModel = new ObservableCollection<CASOrderItem>();
var i = (from m in modelOrderItems select m).ToList();
foreach (dynamic item in modelOrderItems)
{
CASOrderItem orderItem;
orderItem = new CASOrderItem();
orderItem.Createdby = item.Createdby;
orderItem.CreatedDate = item.CreatedDate;
orderItem.ItemMetaPK = item.ItemMetaPK;
orderItem.OrderItem = item.OrderItem;
orderItem.OrderItemID = item.OrderItemID;
orderItem.ParentOrderID = item.ParentOrderID;
orderItem.PrdMainPK = item.PrdMainPK;
orderItem.Quantity = item.Quantity;
orderItem.TacticPkey = item.TacticPkey;
casOrderItemModel.Add(orderItem);
}
return true;
}
The issues are:
1.) The foreach {} block is not iterating, and it just skips the code (even if modelOrderItems has 4 items in it), thereby rendering my casOrderItemModel empty (which I am passing to another code block after this code that supposedly populates the collection).
2.) If I try to convert the IEnumerable to a List, the list doesn't contain any items.
Please let me know how I can fix this issue.
Thank you. :)
Your function takes a parameter IEnumerable<CASOrderItemModel> modelOrderItems on which you call ToList():
var i = (from m in modelOrderItems select m).ToList();
But then you iterate over modelOrderItems, not over i:
foreach (dynamic item in modelOrderItems) { ... }
Evaluating the same enumerable collection twice can result in the second iteration being empty, depending on the source of your collection. Try doing this and remove the unused ToList() line:
foreach (CASOrderItemModel item in modelOrderItems) { ... }
Or if you really want to have that explicit ToList() in there:
foreach (var item in i) { ... }
Finally, since your collection contains a strong typed item CASOrderItemModel, using dynamic makes no sense.
Try changing your IEnumerable<T> with List<T>. My assumption here is that since it is an interface, there has to be an object that holds your list anywhere in the application.

Return every item in a list from a foreach

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.

Categories

Resources