LINQ:在列表中查找频率 = 1 的项目



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

我有一个 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 中频率 = 1 的组,我也丢失了有关人员 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
}

我知道你可能只需要并且想要一个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;

也可以使用哈希码。

最新更新