0

This is a follow up on a related topic found here https://stackoverflow.com/questions/1987485/conditionally-assign-c-var-as-elegant-as-it-gets

if I am doing the following:

  var query = (SearchString == "" ?
    (
         from MEDIA in xdoc.Descendants("MEDIA")
                    select new
                    {
                        PLAY = MEDIA.Element("PLAY").Value,
                        PIC = MEDIA.Element("PIC").Value,
                        TTL = MEDIA.Element("TTL").Value
                    }
    ):


        from MEDIA in xdoc.Descendants("MEDIA")
                    where MEDIA.Element("TTL").ToString().ToLower().Contains(SearchString)
                    select new
                    {
                        PLAY = MEDIA.Element("PLAY").Value,
                        PIC = MEDIA.Element("PIC").Value,
                        TTL = MEDIA.Element("TTL").Value
                    }
    ) ;

How would I declare the query type to make it static at the class level?

Alternatively, in the referenced post Marc Gravell point out a different approach

IQueryable<Part> query = db.Participant;
if(email != null) query = query.Where(p => p.EmailAddress == email);
if(seqNr != null) query = query.Where(p => p.SequenceNumber == seqNr);
...

How would I declare/recode the query in my case? Here is my wild attempts :)

   IEnumerable<XElement> query = xdoc.Descendants("MEDIA");
    if (SearchString != "" )
        query = query.Where(m => m.Element("TTL").ToString().ToLower().Contains(SearchString));

Thank you.

Community
  • 1
  • 1
Marie
  • 39
  • 1
  • 6

1 Answers1

0

How would I declare the query type to make it static at the class level?

You can't. Anonymous types are, well, anonymous... so they don't have a name you can use to declare variables. Your query is of type IEnumerable<something>, but you can't refer to something in your code. So you need to create a specific class that represent the results of your query, and use it instead of the anonymous type.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758