将方法放在foreach循环中c#

时间:2011-01-22 23:10:37

标签: c# visual-studio-2010 c#-4.0 linq-to-xml bing-maps

不确定标题是否真的正确,但这是问题......

我有一个foreach循环填充图钉集合。我需要在其中一个XML元素(Latitude)上做一些“工作”。 “工作”被注释掉了。问题是我无法将这些任务/变量放在何处。无论我把它放在哪里,我都会遇到各种各样的错误。如果需要,我可以详细介绍它,但想知道是否有更好的方法可以做到这一点。它的preey自我解释低于我想要做的但是如果你需要更多的解释让我知道。欢迎任何建议。

  public void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    { 
        var document = XDocument.Load(e.Result);
        if (document.Root == null)
            return;
         var events = from ev in document.Descendants("item")

                      .Where(ev => ev.Element("category") != null)

                     select new 
                     {

                         Title = (ev.Element("title").Value),
                         Description = (ev.Element("description").Value),
                         Category = (ev.Element("category").Value),
                         Latitude = (ev.Element("link").Value),

                      };


         ObservableCollection<Eng> pushPinCollection = new ObservableCollection<Eng>();

        foreach (var ev in events)
         {

             Eng PushPin = new Eng
               (ev.Title, ev.Description, ev.Category)

           // Lat1 = (ev.Latitude),
            //  var items = Lat1.Split('?')[1].Split('&').Select(i => i.Split  ('=')).ToDictionary(o => o[0], o => o[1]); 
            //  var lon = items["lon"]; 
            //  var lat = items["lat"];
            //  var lat1 = Convert.ToDouble(lat);
            //  var lon1 = Convert.ToDouble(lon);
             {

        //Location value below is System.Device.location.Geocoordinate Eng Location
                  Location = new GeoCoordinate(lat1, lon1),
                  Title = ev.Title,
                  Description = ev.Description,
                  Category = ev.Category

             };
            pushPinCollection.Add(PushPin);
         }
         pushPins = pushPinCollection;
         mapItems.ItemsSource = PushPins;

       }

2 个答案:

答案 0 :(得分:1)

一般来说......你应该在“最窄”范围内声明变量。但是,如果您要访问For循环之外的变量,则需要在For循环之外声明它们。可能正好在“foreach(事件中的var ev)”行之上就行了。

答案 1 :(得分:1)

您不能在对构造函数的调用结束和初始化程序之间插入任何代码。有几种方法可以解决这个问题:

Eng pushPin = new Eng(...);  // note the semicolon

// calculations to get lat1 and lon1

pushPin.Location = new GeoCoordinate(lat1, lon1); // Location must have a public Set

// calculations for lat1 and lon 1

Eng PushPin = new Eng(ev.Title, ev.Description, ev.Category)
                  {
                      Location = new GeoCoordinate(lat1, lon1);
                  }

或者如果你有一个采用GeoCoordinate的构造函数:

 Eng PushPin = new Eng(ev.Title, ev.Description, ev.Category, new GeoCoordinate(lat1, lon1));