[英]How can I get only records with a unique property using entity framework and linq?
public class Person
{
public string firstName;
public string lastName;
}
I want a list of all Persons with a unique first name.我想要一个具有唯一名字的所有人员的列表。
Persons table人员表
Tom Haverford
Tom Baker
Amy Pond
Amy Santiago
Trish Walker
Chidi Anagonye
The query should return查询应该返回
Trish, Chidi
I've tried using Distinct and a combination of GroupBy and Select, but those return Trish, Chidi, Tom, Amy
.我试过使用 Distinct 以及 GroupBy 和 Select 的组合,但那些返回
Trish, Chidi, Tom, Amy
。
Demo on dotnet fiddle dotnet fiddle 上的演示
You can Group by
then count
number of duplicated items.您可以
Group by
然后count
重复项目的数量。 After that, you can get the item with count
value equals to 1 like below.之后,您可以获得
count
数值等于 1 的项目,如下所示。
var arr = new []
{
new Person { firstName = "Tom", lastName = "Haverford" },
new Person { firstName = "Tom", lastName = "Baker"},
new Person { firstName = "Amy", lastName = "Pond" },
new Person { firstName = "Amy", lastName = "Santiago"},
new Person { firstName = "Trish", lastName = "Walker"},
new Person { firstName = "Chidi", lastName ="Anagonye" }
};
var result = arr.GroupBy(p => p.firstName).Select(g => new { Name = g.Key, Count = g.Count()});
foreach(var item in result.Where(p => p.Count == 1))
Console.WriteLine(item.Name);
Output输出
Trish
Chidi
You can use group by and count functionality together for this :您可以为此一起使用 group by 和 count 功能:
1. Get a list of all persons from DB : 1.从DB获取所有人员的列表:
var personList = (from p in db.Person select p).ToList(); // I assumed here that your db obj name is 'db' and table name is 'Person'
2. Now apply group by query to get the count of first names : 2. 现在按查询应用分组以获取名字的计数:
var q = from x in personList
group x by x.firstName into g
let count = g.Count()
select new {Count = count, Name = g.First().firstName };
3. Now you can get your final result like this : 3. 现在你可以得到这样的最终结果:
var finalResult = (from p in q where p.Count == 1 select p).ToList();
Happy Coding...快乐编码...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.