Pregunta

¿Cómo debo usar esto en .NET 2.0 ...?

[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable<OperatorField> FindByType(String type)
{
    //  return only selected type
    return (from ce in this.OperatorFields where ce.Type == type select ce).ToList();
}

Utilizo esto en proyectos de 3.5, pero ahora estoy agregando nuevas funcionalidades a un proyecto anterior que no puedo (en este momento) actualizar a 3.5.


Acabo de hacer esto:

[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable<OperatorField> FindByType(String type)
{
    //  return only selected type
    //return (from ce in this.OperatorFields where ce.Type == type select ce).ToList();

    List<OperatorField> r = new List<OperatorField>();

    foreach (OperatorField f in this.OperatorFields)
        if (f.Type == type)
            r.Add(f);

    return r;
}
¿Fue útil?

Solución

¿Todavía puede usar C # 3.0 pero no .NET 3.5? Si es así, mantenga el código como está y use LINQBridge , que es LINQ to Objects implementado para .NET 2.0.

De lo contrario, haga esto:

[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable<OperatorField> FindByType(String type)
{
    List<OperatorField> list = new List<OperatorField>();
    foreach (OperatorField ce in OperatorFields)
    {
        if (ce.Type == type)
        {
            list.Add(ce);
        }
    }
    return list;
}

Otros consejos

¿Algo como esto quizás?

IList<OperatorField> col = new List<OperatorField>();
foreach (OperatorField f in this.OperatorFields)
{
    if (f.Type == type)
        col.Add(f);
}
return col;
[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable<OperatorField> FindByType(String type)
{
    foreach (OperatorField ce in this.OperatorFields)
    {
        if (ce.Type == type)
            yield return ce;
    }
}

Piense en lo que está haciendo la declaración: itera sobre cada elemento en la propiedad OperatorFields, verifica el tipo y luego agrega el elemento a una lista antes de devolver la lista completada.

Entonces tienes

Create new list
For each item in OperatorFields
  if item.Type equals type
    add item to list

return list
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top