user2631382
user2631382

Reputation: 31

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?

Upvotes: 3

Views: 24751

Answers (4)

Roshan Kumar Singh
Roshan Kumar Singh

Reputation: 1

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.

Upvotes: 0

YD1m
YD1m

Reputation: 5905

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

Upvotes: 0

evanmcdonnal
evanmcdonnal

Reputation: 48154

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.

Upvotes: 8

DotNetRussell
DotNetRussell

Reputation: 9863

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

Upvotes: 0

Related Questions