Luke
Luke

Reputation: 109

Is it possible to return an item in a list, for use in another method?

Working with Unity.

Sorry if this seems ridiculous, or if the answer is obvious.

I have a foreach loop which cycles through some items in a list, but only certain objects are subject to a set of further instructions:

(randomValues is an int array which stores seven random numbers, every item in the list has an ID.)

foreach (var item in itemsList)
{
    if(randomValues.Contains(item.itemID))
    { 
        //Code not relevant.         
    }    
}

I want to take whatever items are worked with and use them in another method. So I thought about passing the item out as a parameter for the method, but then realized I have no idea how I'd do that, and I don't know if such a thing is even possible.

Upvotes: 0

Views: 90

Answers (4)

Tarik
Tarik

Reputation: 11209

You can use the following code:

return itemList.where (item => randomValues.Contains(item.itemID));

I selected not to use ToList() to benefit from a lazy evaluation.

Upvotes: 0

paul
paul

Reputation: 22021

var itemsCopy = itemsList.Where(i => randomValues.Contains(i.itemID)).ToList();

Upvotes: 0

Abhishek
Abhishek

Reputation: 7045

Here you go,

var tempList=new List<int>();//assuming int values in list    
foreach (var item in itemsList)
{
    if(randomValues.Contains(item.itemID))
    {
        tempList.Add(item); //add item to temp list
        //some code
    }
}
return tempList;

Upvotes: 0

David
David

Reputation: 219057

Depends on how your objects/methods are structured. Do you need to pass a single item to a method?

foreach (var item in itemsList)
    if (randomValues.Contains(item.itemID))
        SomeOtherMethod(item);

Do you need this current method to filter the list to only the ones which should be later passed to another method?

foreach (var item in itemsList)
    if (randomValues.Contains(item.itemID))
        yield return item;

Do you need to pass a list of matching items from within this method to another method?

var matchingItems = new List<SomeType>();
foreach (var item in itemsList)
    if (randomValues.Contains(item.itemID))
        matchingItems.Add(item);
SomeOtherMethod(matchingItems);

Or even just use LINQ:

SomeOtherMethod(itemsList.Where(i => randomValues.Contains(i.itemID)));

And so on...

Upvotes: 3

Related Questions