Question

How should I use this in .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();
}

I use this in a 3.5 projects, but now I'm adding new functionality to an old project that I cannot (at this time) upgrade to 3.5.


I just did this:

[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;
}
Was it helpful?

Solution

Can you still use C# 3.0 but not .NET 3.5? If so, keep the code as it is and use LINQBridge, which is LINQ to Objects implemented for .NET 2.0.

Otherwise, do this:

[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;
}

OTHER TIPS

Something like this perhaps?

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;
    }
}

Think about what the statement is doing, it's iterating over each item in the OperatorFields property, checking the type and then adding the item to a list before returning the completed list.

So you've got

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

return list
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top