[英]C# Entity Framework / SQL Server count number of matched data
Given a table Foo: 给定一个表Foo:
table Foo (
name,
city,
country,
year,
color,
age
);
Data that is stored in the Foo table: Foo表中存储的数据:
Peter, Brussels, Belgium, 2013, blue, 19
Dirk, Brussels, Belgium, 1999, red, 33
Jean, Paris, France, 2011, blue, 27
Line of data I want to match against database: 我要与数据库匹配的数据行:
Peter, Brussels, Belgium, 2013, blue, 19
==> should give for: ==>应该给出:
row 1: 100% or 6
row 2: 33% or 2
row 3: 16% or 1
Another line of data to test: 另一行数据要测试:
Peter, Paris, France, 2011, green, 36
==> should give for: ==>应该给出:
row 1: 16% or 1
row 2: 0% or 0
row 3: 50% or 3
I could fetch all data in memory and run some C# logic on it, but that would not be the smartest thing. 我可以获取内存中的所有数据并在其上运行一些C#逻辑,但这并不是最明智的选择。
Would it be possible to do this kind of calculation ("% that matches row data") in a single query? 是否可以在单个查询中进行这种计算(“与行数据匹配的%”)?
Bonus: 奖金:
Is it possible to add weights to columns so that column 3 and 5 would add a higher count-weight? 是否可以为列增加权重,以便第3列和第5列会增加较高的计数权重?
Using C# with EF with a code-first approach, and a SQL Server database (stored procedure is not an option as the database could be a different type). 将C#与EF结合使用,采用代码优先方法和SQL Server数据库(存储过程不是一种选择,因为数据库可能是另一种类型)。
Use a ternary conditional operator for each condition which returns 1 or 0, and add each result. 对返回1或0的每个条件使用三元条件运算符,并将每个结果相加。 You could replace the 1s with other numbers to achieve weighting, in which case the value 6.0 in the percentage calculation should be replaced with the sum of the weight values. 您可以用其他数字替换1以实现加权,在这种情况下,百分比计算中的值6.0应该替换为权重值的总和。
foos.Select(x =>
(x.name == "Peter" ? 1 : 0) +
(x.city == "Brussels" ? 1 : 0) +
(x.country == "Belgium" ? 1 : 0) +
(x.year == 2013 ? 1 : 0) +
(x.color == "blue" ? 1 : 0) +
(x.age == 19 ? 1 : 0))
.Select(x => $"{Math.Round(x / 6.0 * 100, 0, MidpointRounding.AwayFromZero)}% or {x}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.