我在找到最有效 解决方案方面遇到了一个小问题。我有一个编号,例如 10 个 student ids。其中一些 ID 是相对的( sibling )。同为兄妹的,只留其中一个作为身份标识,不管哪个,第一个就可以了。
例如学生id
原创
1、2、3、4、5、6、7、8、9、10
其中 1, 2, 3
是一个家庭 sibling ,8, 9
是另一个家庭 sibling 。最后我应该有:
预期
1, 4, 5, 6, 7, 8, 10
我正在循环执行。
更新:
我只是停下来实现它,因为它变得越来越大。这是我脑海中的一幅大图。我只是逐行收集每个给定 ID 的所有兄弟 ID,然后我将逐个迭代。但就像我说的那样,这是在浪费时间。
代码(概念上)
static string Trimsiblings(string ppl) { string[] pids=ppl.Split(','); Stack<string> personid=new Stack<string>(); foreach(string pid in pids) { // access database and check for all sibling // is for each individual pid // such as in example above // row 1: field 1=1, field2=2, field3=3 // row 2: field 1=8, field2=9 query = Select..where ..id = pid; // this line is pesudo code for(int i=0; i<query.Length; i++) { foreach(string pid in pids) { if(query.field1==pid) { personid.Push(pid);
} } } } }
最佳答案
对于高效的代码,必须注意每个 sibling 家族的一个成员(例如,第一个)是无关紧要的,因为它将保留在输出中。也就是说,我们只需要
- 创建一个不得出现在输出中的项目列表
- 实际删除它们
当然,这仅在假设每个 sibling 都实际出现在原始 ID 列表中的情况下才有效。
在代码中:
int[] ids = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int families = new int[2][] {
new int [] {1, 2, 3},
new int [] {8, 9}
};
var itemsToOmit = siblings.
Select(family => family.Skip(1)).
Aggregate((family1, family2) => family1.Concat(family2));
var cleanedIds = ids.Except(itemsToOmit);
编辑:既然你提到你不太熟悉语法,我会做一些进一步的解释
- 我使用的表达式是 extension methods是 System.LINQ 的一部分命名空间
- Select方法将一个序列转换为另一个序列。由于
families
是sequence of sequences,family
将是同一家族中的 sibling 序列(即1, 2, 3
和8, 9
在这种特殊情况下) - Skip方法跳过序列中的一些元素。在这里,我决定始终跳过第一个元素(原因见上文)
- Aggregate方法将序列的元素组合成单个元素。在这里,所有 sibling 的家庭都只是相互连接(除了每个家庭的第一个 sibling 已通过 Skip 省略)
- Except方法返回序列中不作为参数给出的序列中的所有元素。
我希望这能澄清一些事情。
关于c# - 在 C# 中构造树算法的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15491678/