JL.
JL.

Reputation: 81262

C# how to find a value in a List collection

I have a list this list contains a collection of the following class

public class MyFile
{
    public string FileName
    {
        get;
        set;
    }

    public int Position
    {
        get;
        set;
    }
}

So ofc the list definition will look like this:

private List<MyFile> MyFiles = new List<MyFile>();

I can also search the collection using:

MyFile tmpFile = MyFiles.Find(delegate(MyFile item) 
   { return item.FileName == fileName; });

So far looking good, except what I would like to do is return the MyFile that not only matches the file name but that also has the highest value in field pos.

So if the following items exist in the list:

myDocument.doc|1
myDocument.doc|2
myDocument.doc|3
myPDF.pdf|1
myPDF.pdf|2
myPDF.pdf|3

and the value of fileName = "myDocument.doc" in my find method, then I am still missing logic to return myDocument.doc|3 this item, because this has the highest value of pos.

In SQL my query would be

select top 1 * from MyFiles 
where fileName = 'myDocument.doc' 
order by position desc;

Thanks in advance.

Upvotes: 1

Views: 10302

Answers (3)

Marek Karbarz
Marek Karbarz

Reputation: 29294

Can you use Linq? If so, a simple query like this should do:

MyFile file = MyFiles.Where(f => f.FileName == fileName).OrderByDescending(f => f.Position).FirstOrDefault();

Upvotes: 11

Charles Bretana
Charles Bretana

Reputation: 146429

try this:

public class MyFileList: List<MyFile> 
{
    public MyFile this[string filName]
    {
       get 
       {
          int maxPos = int.MinValue;
          MyFile retFile = null;
          foreach(MyFile fil in this)
             if (fil.FileName == filName && 
                 fil.Position > maxPos)
             {
                 maxPos = fil.Position;
                 retFile= fil;
             }
          return retFile;
       }
    }
}

Upvotes: 0

Dathan
Dathan

Reputation: 7446

This is easy using LINQ or extension methods if you're using above .Net 2.0:

MyFile tmpFile = MyFiles.Where(file => file.FileName == "myDocument.doc").OrderByDescending(file => file.Position).FirstOrDefault();

Upvotes: 3

Related Questions