4

我正在努力完成以下任务。任何建议将不胜感激!

我有一个 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

我想找到所有在他们的邮政编码中有唯一名字的人。

到目前为止,我已经尝试对(名字、姓氏、邮政编码)的所有不同组合进行频率计数,然后选择频率 = 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)
                        };

正如我所提到的,即使我现在可以在 g 中选择 freq = 1 的组,我也丢失了有关人员 ID 的所有信息。

我希望我已经把问题说清楚了。在此先感谢您的任何建议!

4

2 回答 2

5
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
}
于 2012-07-05T23:35:48.877 回答
1

我知道你可能只需要并且想要一个 linq 答案:)
但我只需要写一个非 linq 答案:

var dict = new Dictionary<string, Person>(PersonList.Count);

        var uniqueList = new List<Person>();

        foreach (var p in PersonList)
        {
            var key = p.firstname + p.lastname + p.zipcode;
            if (!dict.ContainsKey(key))
                dict.Add(key, p);
            else
                dict[key] = null;
        }

        foreach (var kval in dict)
        {
            if (kval.Value != null)
                uniqueList.Add(kval.Value);
        }

        return uniqueList;

也可以使用哈希码。

于 2012-07-06T00:30:10.987 回答