tags:

views:

56

answers:

2

I have List<T> and I want to find two random name from that List<T> starting with some condition from List using .NET 2.0.

I know its very easy with LINQ but I am stuck with 2.0

I am wondering if I can do something like this

List<foo> list = new List<foo>();
List<foo> newlist = new List<foo>();
Random r = new Random();

list.Add(new foo("1"));
list.Add(new foo("A91"));
list.Add(new foo("A01"));
list.Add(new foo("A71"));
list.Add(new foo("B02"));
list.Add(new foo("B2"));
list.Add(new foo("B03"));
list.Add(new foo("23"));
list.Add(new foo("24"));

string[] searchList = { "A", "B", "C",};

foreach (string name in searchList)
{
   List<foo> templist = list.FindAll(delegate (foo f)
                        {
                             List<foo> templist1 = f.Name.StartsWith(name);
                             {
                                if(templist1.Count>0)
                               {
                                  while (templist.Count != 0)
                                 {
                                    ??.Add(templist1[r.Next(templist1.Count)]);

                                 }
                              retrun ??
                            }
                       }
                       });


 }
A: 

Not return, but yield return.

Daniel Mošmondor
isn't `yield return` a C# 3.0 feature?
CodeInChaos
No, it seems that VS2005 (.net 2.0) supports it. Click on link (I updated it)
Daniel Mošmondor
Yield cannot be used inside an an anonymous method (compiler error) (from your link)
PostMan
Well then, if he wants to use that kind of structure, will have to sacrifice anonymous method and move to real method...
Daniel Mošmondor
+1  A: 

Putting aside that the way I'd personally approach being restricted to .NET 2.0 is by using the 3.5 System.Core dll and copying local (as mentioned by Nick Martyshchenko)...

The actual problem here seems to be that you are not returning the correct type in your anonymous delegate List<T>.FindAll takes a Predicate<T> delegate. Predicate returns a bool.

List<T>.FindAll is NOT like the LINQ where method at all. It is not lazy. That is, it is not an IEnumerable that yields on enumeration. FindAll returns a List<T> (already enumerated).

Maybe I'm not understanding your requirements here, but why not do this:

List<foo> templist = list.FindAll(delegate (foo f)
                    {
                         bool itemStartsWith = f.Name.StartsWith(name);

                         if(itemStartsWith)
                         {
                            return true;
                         }
                         return false;
                    });
JeffN825
I may be misunderstanding but I think the op wants this list shuffled after the fact
Sam Saffron