简体   繁体   中英

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.

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

如果您使用的是.Net 2.0以上版本,则使用LINQ或扩展方法很容易:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM