如何改进以下代码?

时间:2012-05-09 13:51:08

标签: c#-4.0

有没有更好的方法来编写以下程序(我相信它可以是如何)

for (int i = 0; i < relevantElements.Count(); i++)
            {
                switch (len)
                {
                    case 1: result.Add(new ContextElements
                    {
                        CultureName = GetElementValues(relevantElements[0], applicationType)
                        ,
                        AffId = null
                        ,
                        EmailAddress = null
                    }); 
                        break;
                    case 2:
                    result.Add(new ContextElements
                    {
                        CultureName = GetElementValues(relevantElements[0], applicationType)
                        ,
                        AffId = GetElementValues(relevantElements[1], applicationType)
                        ,
                        EmailAddress = null
                    }); 
                        break;
                    case 3:
                        result.Add(new ContextElements
                        {
                            CultureName = GetElementValues(relevantElements[0], applicationType)
                            ,
                            AffId = GetElementValues(relevantElements[1], applicationType)
                            ,
                            EmailAddress = GetElementValues(relevantElements[2], applicationType)
                        });
                        break;
                }
            }

由于

编辑

我有一个源xml文件

<?xml version="1.0" encoding="utf-8"?>

<RootElement>

  <HomeSite>

   <Context enabled="1" active="1">

      <Culture>en-us</Culture>

      <Affiliate>0</Affiliate>

      <EmailAddress>sreetest@test.com</EmailAddress>

      <Password>sreesree1</Password>

    </Context>

  </HomeSite>

  <ResourceManager>

    <Context enabled="1" active="1">

      <Culture>en-us</Culture>

      <Affiliate>0</Affiliate>

    </Context>

  </ResourceManager>  

  <Purchase>

     <Context enabled="1" active="1">

      <PurchaseUrl>http://purchase.mcafee.com?culture=en-us&amp;affid=0</PurchaseUrl>

    </Context>

    <Context enabled="0" active="0">

      <PurchaseUrl>http://purchase.mcafee.com?culture=en-gb&amp;affid=0</PurchaseUrl>

    </Context>

  </Purchase>  

</RootElement>

对于“HomeSite”Applcation Type,可以找出“Context”元素下的3个元素,即Culture,Affiliate,EmailAddress。但是这会从其他应用程序类型“ResourceManager”和“Purchase”中发生变化。我还有

下的自定义实体
public class ContextElements

{
    public string CultureName { get; set; }

    public string AffId { get; set; }

    public string EmailAddress { get; set; }

}

挑战在于我必须在运行时填充属性值。它不能超过3个。

我的完整程序(但需要改进代码)

class Program
    {       
        static void Main(string[] args)
        {
            XDocument xmlSkuDescDoc = null;

            xmlSkuDescDoc = XDocument.Load(@"D:\Config.xml");

            string applicationType = ApplicationType.Purchase.ToString();

            var result = new List<ContextElements>();

            var elementCollection = new List<string>();


            (from data in xmlSkuDescDoc.Descendants(applicationType)
             select data)
                     .Descendants("Context")
                     .Elements()
                     .ToList()
                     .ForEach(i => elementCollection.Add(i.Name.ToString()));

           //Exclude unwanted elements
            var relevantElements = elementCollection.Except(new List<string> { "Password" }).ToList();

            int len = relevantElements.Count();

            for (int i = 0; i < relevantElements.Count(); i++)
            {
                switch (len)
                {
                    case 1: result.Add(new ContextElements
                    {
                        CultureName = GetElementValues(relevantElements[0], applicationType)
                        ,
                        AffId = null
                        ,
                        EmailAddress = null

                    }); 
                        break;
                    case 2:
                    result.Add(new ContextElements
                    {
                        CultureName = GetElementValues(relevantElements[0], applicationType)
                        ,
                        AffId = GetElementValues(relevantElements[1], applicationType)
                        ,
                        EmailAddress = null
                    }); 
                        break;
                    case 3:
                        result.Add(new ContextElements
                        {
                            CultureName = GetElementValues(relevantElements[0], applicationType)
                            ,
                            AffId = GetElementValues(relevantElements[1], applicationType)
                            ,
                            EmailAddress = GetElementValues(relevantElements[2], applicationType)
                        });
                        break;
                }
            }

           // //just for printing
           result.ForEach(i => Console.WriteLine(string.Format("CultureName = {0} , AffId = {1} , EmailAddress = {2} ", i.CultureName, i.AffId, i.EmailAddress)));

            Console.ReadKey();

        }

        private static string GetElementValues(string elementName,string applicationType)
        {
             XDocument xmlSkuDescDoc = null;

            xmlSkuDescDoc = XDocument.Load(@"D:\Config.xml");

            return (from data in

                             (from data in xmlSkuDescDoc.Descendants(applicationType)

                              select data).Descendants("Context")

                    select new { Value = (string)data.Element(elementName)}).FirstOrDefault().ToString();
        }

        public enum ApplicationType
        {
            HomeSite = 1
            ,
            ResourceManager
                ,
            ApplicationProvisioning
                ,
            Purchase
                ,
            GAC
           , WebSVCService
        }
    }

3 个答案:

答案 0 :(得分:1)

具有相同行为的代码的直接机械重写将是

for (int i = 0; i < relevantElements.Count(); i++)
{
    result.Add(new ContextElements
    {
        CultureName = GetElementValues(relevantElements[0], applicationType),
        AffId = len < 2 ? null : GetElementValues(relevantElements[1], applicationType),
        EmailAddress = len < 3 ? null : GetElementValues(relevantElements[2], applicationType),
    }); 
}

那就是说,我不知道这个代码试图做什么,或者它是否正确。

答案 1 :(得分:0)

嗯,你可以用这种方式略微改进代码:

var cultureName = GetElementValues(relevantElements[0], applicationType);
AffIdType affId = null; // replace with the actual type
EmailAddressType emailAddress = null; // ditto

switch (len)
{
    case 2:
        AffId = GetElementValues(relevantElements[1], applicationType);
        break;
    case 3:
        AffId = GetElementValues(relevantElements[1], applicationType);
        EmailAddress = GetElementValues(relevantElements[2], applicationType);
        break;
}
for (int i = 0; i < relevantElements.Count(); i++)
{
    result.Add(new ContextElements
    {
        CultureName = cultureName,
        AffId = affId,
        EmailAddress = emailAddress
    });
}

(我假设您的代码不依赖于AffIdEmailAddress是不同的对象。)

答案 2 :(得分:0)

至少你能做到:

var culture = GetElementValues(relevantElements[0], applicationType); 
var affId = GetElementValues(relevantElements[1], applicationType); 

for (int i = 0; i < relevantElements.Count(); i++) 
        { 
            switch (len) 
            { 
                case 1: 
                result.Add(new ContextElements 
                { 
                    Culture = culture, 
                    AffId = null, 
                    EmailAddress = null 
                });  
                    break; 
                case 2: 
                result.Add(new ContextElements 
                { 
                    Culture = culture, 
                    AffId = affId,
                    EmailAddress = null 
                });  
                    break; 
                case 3: 
                    result.Add(new ContextElements 
                    { 
                        Culture = culture, 
                        AffId = affId,
                        EmailAddress = GetElementValues(relevantElements[2], applicationType) 
                    }); 
                    break; 
            } 
        }