在列表中设置null会导致其他列表中的空值

时间:2013-11-19 07:40:13

标签: c# collections

我有两个列表,我想从中获取不同的项目

SearchElement[] criteria = new SearchElement[] { 
    new SearchElement 
    { 
         Comparison = "=", 
         FieldName = "CableProperty.ProjectId", 
         FieldValue = int.Parse(comboBoxSource.SelectedValue.ToString()), 
         LogicalOperator = "" }
     };

sourceCables = client.GetCables(criteria, null, "Cores,CableProperty,CableProperty.CableApplication").ToList();
criteria = new SearchElement[] { 
     new SearchElement 
     { 
         Comparison = "=", 
         FieldName = "CableProperty.ProjectId", 
         FieldValue = int.Parse(comboBoxDestination.SelectedValue.ToString()), 
         LogicalOperator = "" }
     };

destinationCables = client.GetCables(criteria, null, "Cores,CableProperty,CableProperty.CableApplication").ToList();
diffCables = sourceCables.Except(destinationCables, new CableComparer())
                          .ToList();

现在我在diffcable中有不同的项目。有时我想设置 diffCable.CableProperty.CableApplication = null; 但是当我这样做时,源列表中的所有导航Porperty(CableApplication)也被设置为null。 这是代码

if (destinationCableApplications.Contains(diffCable.CableProperty.CableApplication, new CableApplicationComparer()))
{
   criteria = new SearchElement[] { new SearchElement { Comparison = "=", FieldName = "ProjectId", FieldValue = int.Parse(comboBoxDestination.SelectedValue.ToString()), LogicalOperator = "" }};
   cableApplication = client.GetCableApplications(criteria, null, "").SingleOrDefault();
   diffCable.CableProperty.CableApplication = null;
}

在这一行之后兴致勃勃地

diffCable.CableProperty.CableApplication = null;

所有

  sourcecables[0].CableProperty.CableApplication

  sourcecables[1].CableProperty.CableApplication

  .....

  sourcecables[100].CableProperty.CableApplication

设置为null

当我在diffcable中将null设置为navigation属性时,我该怎么办才能不丢失sourcelist中的导航属性?

2 个答案:

答案 0 :(得分:0)

您在没有意识到的情况下通过引用进行复制。查看克隆对象或创建新列表。

List<int> newCopyList = new List<int>(originalList);

答案 1 :(得分:0)

最简单的方法是使用MemoryStream .. 这是一个样本,

    [Serializable]
    public class temp
    {
       public int a;
    }
    class Program
    {
        public static T DeepClone<T>(T a)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, a);
                stream.Position = 0;
                return (T)formatter.Deserialize(stream);
            }
        }
        static void Main(string[] args)
        {
            List<temp> list1 = new List<temp>();
            list1.Add(new temp { a = 1 });
            list1.Add(new temp { a = 2 });
            list1.Add(new temp { a = 3 });
            List<temp> list2 = DeepClone<List<temp>>(list1);
            list1[1].a = 4;
            Console.WriteLine(list2[1].a);
            Console.ReadKey();
        }
    }

注意:class必须是Serializable。 这适用于所有值和引用类型。