0

i have two FileInfo[] Array's and i want compare the Files with identical Names about their File Size and Last Modified Date. But how can i select a File out of a FileInfo[] with a specific Name?

My Code doesnt work, because i cant use FileInfo.Select to get a new FileInfo out. Any clues?

        foreach (FileInfo origFile in fiArrOri6)
        {
            FileInfo destFile = fiArrNew6.Select(file => file.Name == origFile.Name);
            if (origFile.Length != destFile.Length || origFile.LastWriteTime != destFile.LastWriteTime)
            {
                //do sth.
            }
        } 

Thanks for any help :)

btw. Any other charming solution for this Problem would be great. btw. #2 : does someone has good learning material for FileInfo?

lukiffer
  • 11,025
  • 8
  • 46
  • 70
The_Holy_One
  • 321
  • 5
  • 16

3 Answers3

5

You could use the FirstOrDefault that takes a filter

FileInfo destFile = fiArrNew6.FirstOrDefault(file => file.Name == origFile.Name);

Or, if you don't want the default, you can use the equivalent First that takes a filter

FileInfo destFile = fiArrNew6.First(file => file.Name == origFile.Name);
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
2

destFile is not a FileInfo, it is a linq query. Change its name to something like fileQuery and then

var fileQuery = fiArrNew6.Where(file => file.Name == origFile.Name);
var destFile = fileQuery.FirstOrDefault();
if (destFile != null)
    //...

Bonus tip: avoid names like fiArrNew6; they're confusing. Descriptive names like newFiles are easier to read, and they allow you to change your code without having to rename your variables.

phoog
  • 42,068
  • 6
  • 79
  • 117
  • +1 Definitely agree with your bonus tip :) I always say concise is not short only it is short AND descriptive. Emphasis should be more on descriptive – Justin Pihony Apr 17 '12 at 15:24
1

Change the Select into a Where:

FileInfo destFile = fiArrNew6.Where(file => file.Name == origFile.Name).First();

The Where will return an IEnumerable<FileInfo>, using First with that will ensure the first such occurrence is used (if there are none, it will throw an exception).

Oded
  • 489,969
  • 99
  • 883
  • 1,009