2017-09-27 70 views
-1

大家好我有3類添加數據後如下C#類爲xml使用LINQ

public class Main 
{ 
    public List<B> BList{ get; set; } 
} 
public class B 
{ 
    public B() 
    { 
     ListA = new List<A>(); 
    } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Email { get; set; } 
    public List<A> ListA { get; set; } 
} 
public class A 
{ 
    public int Rating { get; set; } 
    public int Weightage { get; set; } 
} 

我試圖使用LINQ如下將其轉換爲XML

Main main = new Main(); 
var xEle = new XElement("Root", 
    from x in main.BList 
    from te in x.A 
    select new XElement("Child", 
     new XElement("Weightage", te.Weightage), 
     new XElement("FName", x.FirstName), 
     new XElement("LName", x.Email))); 

這是給我輸出如下

<Root> 
    <Child> 
    <Weightage>20</Weightage> 
    <FName>ABC</FName> 
    <LName>[email protected]</LName> 
    </Child> 
    <Child> 
    <Weightage>20</Weightage> 
    <FName>ABC</FName> 
    <LName>[email protected]</LName> 
    </Child> 
</Root> 

我需要的是如下

<Root> 
    <Child> 
    <Weightage>10</Weightage> 
    <FName>ABC</FName> 
    <LName>[email protected]</LName> 
    </Child> 
    <Child> 
    <Weightage>20</Weightage> 
    <FName>ABC</FName> 
    <LName>[email protected]</LName> 
    </Child> 
</Root> 

提琴手這裏https://dotnetfiddle.net/x6Hj01

+0

你能某處添加一些字符來表示(電流輸出與預期輸出之間)的差異,我不能告訴ATM - 使用在線比較,現在看到的差異(20的權重應該是10) – EpicKip

+3

也許使用序列化?轉換爲xml字符串並返回到對象時,我發現它很有用。 – japesu

+0

輸出的孩子的體重是相同的,即20 –

回答

5

問題:

你的問題是不是與LINQ而是你如何填充數據:

Master m=new Master(); 
m.BList =new List<B>(); 

B b=new B(); 
b.FirstName ="ABC"; 
b.Email="[email protected]"; 

A a=new A(); //Line 1 
a.Rating = 1; 
a.Weightage =10; 

b.ListA.Add(a); //Line 2 

a.Rating = 2; <--- problem here 
a.Weightage =20; 

b.ListA.Add(a); //Line 3 
m.BList.Add(b); 

您實例a只一個(在「第1行」),然後填充數據並將其添加到列表中(在「第2行」)。然後你重新分配數據並將其添加到列表中(在「第3行」)。

當您再次將值分配到a時,您實際上仍在更新與以前相同的參考。因此,您在列表中使用相同的對象兩次,並使用相同的值,因爲它是相同的對象。

解決方案:

爲了解決它只是問題的行前添加A a = new A()

建議和改進:

  1. 一個更清潔的方式一起是使用對象初始化:

    Master m=new Master 
    { 
        BList = new List<B> 
        { 
         FirstName = "ABC", 
         Email = "[email protected]", 
         AList = new List<A> 
         { 
          new A { Rating = 1, Weightage = 10 }, 
          new A { Rating = 1, Weightage = 20 }, 
         } 
        } 
    }; 
    
  2. 至於構建你的XML的方式,我建議使用 序列化。 Look here for some examples

  3. 另一項改進是這樣初始化集合: (可能從C#6.0)

    public class Main 
    { 
        public List<B> BList { get; set; } = new List<B>() 
    } 
    public class B 
    { 
        public List<A> ListA { get; set; } = new List<A>() 
    } 
    
+0

是的,這就是爲什麼我標記此_off-topic尋求調試幫助(「爲什麼不是這個代碼工作?」)_ – SeM

+0

OP某處發佈初始化代碼或者你在猜測?我不能在任何地方看到代碼,所以有點困惑 - 人們upvoting,但對我來說,它看起來像你正在調試你認爲存在的代碼,不覺得有什麼upvotable ... – Chris

+1

@Chris - 沒有承擔任何東西 - 代碼在提琴手鍊接 –

0

另一種方式來序列化你的數據是使用DataContract序列化。

你可以找到更多信息on msdn Here.

這將是比你的解決方案:)容易