【问题标题】:other way to add item to List<>将项目添加到 List<> 的其他方式
【发布时间】:2010-03-24 21:50:51
【问题描述】:

在我的other question 你可以看到我的arr 结构和PriorityQueue 集合的代码。我通常会像这样将项目添加到这个集合中:

arr.PriorityQueue.Add(new element((value(item, endPoint) + value(startPoint, item)),item));

我很好奇还有其他方法可以做到这一点(将元素(即结构)对象添加到列表中)?例如以 lambda 方式?我只是渴望知识:)

【问题讨论】:

  • 其他问题,而不是“其他问题”。 Ask 只是一个动词,不能用作名词,尽管 question 可以用作名词和动词。英语可能很棘手......我敢肯定,我的母语听起来像个白痴:)
  • @Mike - 对某些人来说,学习英语是个大问题!
  • 哈哈,别把他弄糊涂了!我没有责怪他,只是提供一个更正。花一些时间在livemocha.com 上,你会忍不住提供一些提示:)
  • @Netmajor - 你比我更好。 (我假设你是男性)
  • 首先,你的结构根本不应该是结构,它们应该是类。包含引用类型的结构大多没有意义,而可变结构很难使用。

标签: c# list lambda


【解决方案1】:

要将新对象添加到列表中,您需要对其进行实例化。

你这样做的方式是正确的,这个操作没有lambda语法或其他syntactic sugar。

【讨论】:

    【解决方案2】:

    另一种方法是使用List.AddRange。它接受IEnumerable&lt;T&gt;,因此您可以将T 的任何集合传递给它,包括数组或Linq 表达式的结果:

    importantItems.AddRange(allItems.Where(item => item.IsImportant));
    

    【讨论】:

    • 根据您的代码...也许我可以这样做: arr.PriorityQueue.Add(new element(key,value)(key=>((value(item, endPoint) + value (startPoint, item))),value=>item));我确信我看到了类似的东西!原文如此!;/
    • 你在考虑对象初始化语法吗?例如new element { key = x, value = y }
    【解决方案3】:
      arrays arr = new arrays();
            arr.PriorityQueue = new List<element>(
                new [] { 
                    new element {node = 1, priority =2 }, 
                    new element { node = 2, priority = 10}
                    //..
                    //..
                });
    
    
            arrays arr2 = new arrays();
            arr2.PriorityQueue = new List<element>(
                arr.PriorityQueue
                );
    
    
            arrays arr3 = new arrays();
            arr3.PriorityQueue = new List<element>(arr2.PriorityQueue.FindAll(z => (1 == 1)));
    
    
            arrays arr4 = new arrays();
            arr4.PriorityQueue = new List<element>(arr3.PriorityQueue.ToArray());
    

    【讨论】:

    • 我需要一段时间才能看到这个数组依赖关系:P 一些牵强的例子.. 但这是我想要的。谢谢;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    相关资源
    最近更新 更多