问题描述:

what's the best way to return a List from a list of Lists of a base class based on string passed in. I've got:

public List<myBaseData> FindFromListofLists(string aClass, List<List<myBaseData>> data)

{

foreach (var item in data)

{

foreach(myBaseData baseData in item)

{

if (baseData.ToString().CompareTo(aClass) == 0) //not sure if this is the best way as if the class overides the toString method...

return item;

}

}

return null;

}

I'm sure there's a better way to do this. Any help would be appreciated.

网友答案:

Try -

public List<myBaseData> FindFromListofLists(
      string aClass, List<List<myBaseData>> data)
{

  return data.Find(
      item => item
              .Where(d => d.ToString().CompareTo(aClass) == 0)
              .Count() > 0);

}

You can also try to write it as -

return data.Find(item => item.Select(x => x.ToString()).Contains(aClass));

Please note that the code is untested :P

网友答案:

Is this what you need?

How to Union List<List<String>> in C#

And then you can use the .Where() method to narrow down the results to those matching aClass.

网友答案:

you can use:

            if (((List<myBaseData>)item).Contains(aClass)) ;
            {
                return (item);
            }

instead of your second "foreach". and that's the great thing about dynamic lists.

网友答案:

I would use a Dictionary<string, List<myBaseData>> or Dictionary<Type, List<myBaseData>> insted of List<List<myBaseData>>

The Dictionary-s TryGet method does exactly what you need in FindFromListofLists

网友答案:

I think what you are trying to achieve is this.

public class MyBaseClass{}
public class MyChildClass : MyBaseClass{}

then somewhere else you want to return only the MyChildClass objects. this is what you need to do:

public IEnumerable<MyBaseClass> GetFilteredObjects(Type type, List<List<MyBaseClass>> lists)
{
  foreach(var list in lists)
  {
    foreach(var item in list)
    {
      if(item.GetType() == type)
        yield return item;
    }
  }
}

then you call this method like this:

var myChildClasses = GetFilteredObjects(typeof(MyChildClass), listOfLists);

Hope this is what you are looking for.

相关阅读:
Top