我正在努力完成以下任务.任何建议将不胜感激!
我有一个Person对象列表,如下所示:
public class Person {
private string firstname {get; set}
private string lastname {get; set}
private string zipcode {get; set;}
private string id {get; set;}
private int freq = 1;
public Person(...) {...}
}
List<Person> PersonList = new List<Person>; //Gets populated with Person objects
Run Code Online (Sandbox Code Playgroud)
我想找到所有在其邮政编码中都有唯一名称的人.
到目前为止,我已尝试对(firstname,lastname,zipcode)的所有不同组合执行频率计数,然后选择频率= 1的组合.但是,我会丢失有关这些人的ID的所有信息.尽管进行了分组操作,我还是需要一种保留原始Person对象的方法.
以下是我上面提到的频率计数,但它不是我想要的结果:
var QueryFreqAnalysis =
from p in PersonList
group p by new { p.firstName, p.lastName, p.zipcode } into g
select new {
fName = g.Key.firstname,
lName = g.Key.lastname,
zip3 = g.Key.zipcode,
freq = g.Sum(p => p.freq)
};
Run Code Online (Sandbox Code Playgroud)
正如我所提到的,即使我现在可以选择g中具有freq = 1的组,但我已经丢失了有关Person ID的所有信息.
我希望我已经把问题弄清楚了.在此先感谢您的任何建议!
from p in PersonList
// Group by name and zip
group p by new { p.firstName, p.lastName, p.zipcode } into g
// Only select those who have unique names within zipcode
where g.Count() == 1
// There is guaranteed to be one result per group: use it
let p = g.FirstOrDefault()
select new {
fName = p.firstname,
lName = p.lastname,
zip3 = p.zipcode,
id = p.id
}
Run Code Online (Sandbox Code Playgroud)