balexandre
balexandre

Reputation: 75083

Converting LINQ to .NET 2.0

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

Upvotes: 3

Views: 2047

Answers (4)

daz-fuller
daz-fuller

Reputation: 1231

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

Upvotes: 0

ba__friend
ba__friend

Reputation: 5903

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

Upvotes: 1

cwap
cwap

Reputation: 11287

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;

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500555

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

Upvotes: 12

Related Questions