LINQ Intersect Problem

  • Thread starter Thread starter MitchW
  • Start date Start date
M

MitchW

Hello,

I have the following code:

DirectoryInfo pdfDirectory = new DirectoryInfo(@"..\Documents");
var files = from f in pdfDirectory.GetFiles("*.pdf")
select new { Filename =
Path.GetFileNameWithoutExtension(f.FullName) };
gvFiles.DataSource = files;
gvFiles.DataBind();

XDocument doc = XDocument.Load(@"..\Documents\FARList.xml");
var matches = from employees in doc.Descendants("employee")
select new { Name =
(string)employees.Attribute("name"), FileName =
(string)employees.Attribute("filenameprefix") };
gvXML.DataSource = matches;
gvXML.DataBind();


I want to find the intersection between these on FileName, but when I do

var finalresult = matches.Intersect(files);

the compiler complains that the type arguments for the method cannot be
inferred.

I am not sure what I am missing?

Any help would be greatly appreciated. Thanks in advance.

--mitch
 
MitchW said:
I have the following code:

DirectoryInfo pdfDirectory = new DirectoryInfo(@"..\Documents");
var files = from f in pdfDirectory.GetFiles("*.pdf")
select new { Filename =
Path.GetFileNameWithoutExtension(f.FullName) };
gvFiles.DataSource = files;
gvFiles.DataBind();

XDocument doc = XDocument.Load(@"..\Documents\FARList.xml");
var matches = from employees in doc.Descendants("employee")
select new { Name =
(string)employees.Attribute("name"), FileName =
(string)employees.Attribute("filenameprefix") };
gvXML.DataSource = matches;
gvXML.DataBind();


I want to find the intersection between these on FileName, but when I do

var finalresult = matches.Intersect(files);

the compiler complains that the type arguments for the method cannot be
inferred.

Your first anonymous type has one property named 'Filename', your second
anonymous type has two properties, one named 'Name', one named
'FileName'. It is not clear how to compare objects of those types for
the Intersect LINQ operator. You at least need to use anonymous types
with the same number of properties with the same name.
Or you need to define a class and define an IEQualityComparer for that
class. Then your queries need to construct instances of the class and
the Intersect method as its second argument takes an instance of the
comparer.
 
Back
Top