user1372448
user1372448

Reputation: 437

The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'

I am learning LINQ and was trying out this example related to select clause.

var q = from c in xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
                   .Select(n => new { SiteName = n.Element("name").Value});

The above query is giving me an error:
The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.

What is wrong int the above syntax?

Apart from the above, I have to convert the selected options ToDictionary. How can be done in the same query via LINQ?

The third question that I had in my mind was about different syntax for writing the same query (e: the second method writing example below). What syntax is preferred and why?

from c in xmlDoc.Descendants
where c.Attriubute("technical").Value == "true"
select c.Element("site").Value;

Upvotes: 2

Views: 5390

Answers (1)

Shoaib Shaikh
Shoaib Shaikh

Reputation: 4585

1. you have mixed lambda expression with linq syntax. started with linq and end with lambda expression. try this

 var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
                   .Select(n => new { SiteName = n.Element("name").Value});

or you should be using the whole query in linq

var q = from c in xmlDoc.Descendants("site") where c.Attribute("technical").Value == "true"
                   select new { SiteName = c.Element("name").Value};

2. just use ToDictionary in the end of query

var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
                   .Select(n => new { SiteName = n.Element("name").Value,Key= n.Element("id").Value }).ToDictionary(n=>n.Key,l=>l.SiteName);

n=>n.Key will the key for dictionary and l=>l.siteName will be value.

3. There are two ways of create such queries one is using linq other is using methods that uses lambda expressions as parameter. both are easy, linq is somehow like SQL query while Methods use lambda are more like a short hand for manipulating data by description methods. i personally like method oriented way with lambda as its more sequentially readable.

Upvotes: 3

Related Questions