开发者

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 retur开发者_开发技巧n 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.


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();


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();


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜