views:

623

answers:

1

Hi,

I have a bunch of dropdownlists which I populate from an xml file using linq. I've tried the following to populate them and it somehow works, the only problem is that when an element is missing e.g. subtitle I get an empty space in the dropdownlist. Also I don't get to have the distinct values of each dropdownlist but instead all values. See code below

 var feeds = (from item in doc.Descendants("item")

                     select new
                     {
                         channel = (string)item.Element("channel") ?? null,
                         specialtoken = (string)item.Element("specialtoken") ?? null,
                         subchannel = (string)item.Element("subchannel") ?? null,
                         subtitle = (string)item.Element("subtitle") ?? null,
                     }).ToList().Distinct();


        cboChannel.DataSource = feeds;
        cboChannel.DataBind();

        cboSpecialToken.DataSource = feeds;
        cboSpecialToken.DataBind();

        cboSubChannel.DataSource = feeds;
        cboSubChannel.DataBind();

        cboSubtitle.DataSource = feeds;
        cboSubtitle.DataBind();
     ...And so on....

Is there a better way than to split each value item into a seperate query e.g. ?

Cheers, Chris

var specialtoken = (from item in doc.Descendants("item")
                     select new
                     {
                         specialtoken = (string)item.Element("specialtoken") ?? null,
                     }).ToList().Distinct();


var channel= (from item in doc.Descendants("item")
                     select new
                     {
                         channel = (string)item.Element("channel") ?? null,
                     }).ToList().Distinct();
etc. etc.
+1  A: 

I think the easiest way is to keep the original query but then do a sub query for each of the drop downs that ensures there is a value in the item they care about.

cboChannel.DataSource = feeds.Where(x => !String.IsNullOrEmpty(x.channel)).ToList();

I find this to be much more concise

JaredPar
hmmh, that's what I thought. Seems there is no real elegant way to handle this situation. Thanks anyway for the tip.
Chris