linq query not working

Go To StackoverFlow.com

0

I have the following query:

            var req= (from tl in resultlist
                           where (tl.Message.StartsWith("Do not return") && tl.Type == "Int") && 
                                 (tl.Note.StartsWith("Do no return") && tl.Type == "Ext")
                           select tl).Any();

I am trying to see if there are records where Message starts with "Do not return" and Type is "Int" and there is another message where Note start with "Do no return" and Type is "Ext".

Seems like my query is wrong as not returning anything.

2012-04-04 21:08
by Nate Pet
You're comparing tl.Type with both "Int" and "Ext", and not returning a result unless it's both (which it naturally can't be) To get help doing what you really intend to do, I think you need to explain a little more in detail what you're attempting to do - Joachim Isaksson 2012-04-04 21:10
need more info, provide the classes, what you are calling this out of, EF, NHB, Collections... we need more info - CrazyDart 2012-04-04 21:10


0

var intMessages = from tl in resultlist
                  where tl.Message.StartsWith("Do not return") 
                        && tl.Type == "Int"
                  select tl;
var extMessages = from tl in resultlist
                  where tl.Message.StartsWith("Do not return") 
                        && tl.Type == "Ext"
                  select tl;

var intAndExtMessages = intMessages.Any() && extMessages.Any();

This will ensure that in the result set there are some "Do not return" messages which start with "Int" AND in the same result set are some other messages which start with "Ext"

The function (the condition in query) checks if the source element meets some requirements so if you check for the same object's Type to be "Int" and "Ext" is not possible, since can't have two string values in the same time.

On the other hand you need to find out if in the resultlist exist items of two different types or for two exclusive conditions, so this it can't be done in a single iteration (each LINQ query is an iterator in the end..).

2012-04-04 21:14
by Adrian Iftode
It looked like he was looking for tl.Note.StartsWith and EXT or tl.Message.StartsWith and INT. This would give him false results according to the question - Ryan Bennett 2012-04-05 18:48
@RyanBennett, the key phrase here is "and there is another message - Adrian Iftode 2012-04-05 18:50


1

You probably want to change that && to a || as one of the comments (Joachim Isaksson) above points out. You are asking for a property (.Type) to exist in 2 different ways on one entity. That is not possible.

Try

req= (from tl in resultlist 
    where (tl.Message.StartsWith("Do not return") && tl.Type == "Int") ||
    (tl.Note.StartsWith("Do no return") && tl.Type == "Ext")
    select tl).Any(); 
2012-04-04 21:19
by Ryan Bennett
Ads