Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Wednesday, August 10, 2011 3:45 PM
I have a series of List<int> collections. I'll get an int value, and with that value I check the List<int> collections to see which collection it's in. Each List<int> collection has a distinct set of numbers, so there's only 1 match for any int passed in. I was doing a series of if statements to see which one it belonged to, but I'd like to refactor it to something more manageable. Here's what I tried:
List<List<int>> masterList = new List<List<int>>()
{ firstList, secondList, thirdList, fourthList };
List<int> currentList =
listOfLists.Select(list => list.Contains(someInteger)).FirstOrDefault();
I get an error that C# can't convert bool to List<int>. What I want to do is return the List<int> within the masterList that contains 'someInteger'. Any advice?
All replies (5)
Wednesday, August 10, 2011 3:47 PM âś…Answered
Use Where() instead of Select().Tan Silliksaar milemarx.com
Wednesday, August 10, 2011 4:06 PM
You can also pass the condition to the FirstOrDefault:
List<int> currentList = listOfLists.FirstOrDefault(list => list.Contains(someInteger));
Wednesday, August 10, 2011 5:10 PM
Or this one :)
List<int> currentList = listOfLists.Find(list => list.Contains(searchToken));
Please mark this post as answer if it solved your problem. Happy Programming!
Wednesday, August 10, 2011 7:57 PM
The humiliation! I was looking right at it and didn't see the lack of the where expression. I've been jamming the code too long. Thanks for all the replies. They all look viable. I tested the first solution, and it works, so I'll go with that. Thanks again.
Wednesday, August 10, 2011 8:21 PM
Hi Ironwill,
if you only want to ckeck if an item exists you can call Any():
List<int> currentList =
listOfLists.SingleOrDefault(list => list.Any(intElement => Equals(someInteger, intElement));
You can replace SingleOrDefault() with FirstOrDefault() if it is sure that the lists are disjuctive, or even First() if it sure that the integer is contained by any of the lists. But even if you're sure, catching the exception when calling Single..() is always a good idea.
Hope to be helpful, good luck!
"It's time to kick ass and chew bubble gum... and I'm all outta gum." - Duke Nukem