我正在執行一項任務,該任務要求我搜索資料庫以回傳用戶輸入的城市中的公司名稱。
我創建的方法可以正常作業并完成預期的作業,但是有兩個問題:
- 它在第一條
foreach陳述句中列印了 6 次而不是僅一次。 - 它沒有在第一條
foreach陳述句中回傳正確數量的客戶。
這是完整的方法:
static void ReturnCities()
{
WriteLine("Enter the name of a city: ");
string? city = ReadLine();
using (var db = new Northwind())
{
// query to find all customers in the
// city that was entered
var query = db.Customers
.Where(customer => customer.City == city)
.Select(customer => new
{
customer.City
});
// prints a statement with how many customers
// are in the city entered
foreach (var item in query)
{
WriteLine("There are {0} customers in {1}: ",
arg0: item.City.Count(),
arg1: item.City);
}
// query to return a list of all customers
// in the city entered
var query2 = db.Customers
.Where(customer => customer.City == city)
.Select(customer => new
{
customer.CompanyName
});
foreach (var item2 in query2)
{
WriteLine($" {item2.CompanyName} ");
}
}
}
當前的輸出是:
Enter the name of a city:
London
There are 6 customers in London:
There are 6 customers in London:
There are 6 customers in London:
There are 6 customers in London:
There are 6 customers in London:
There are 6 customers in London:
Around the Horn
B's Beverages
Consolidated Holdings
Eastern Connection
North/South
Seven Seas Imports
除了陳述句之外,我不確定是什么導致了第一個問題,foreach可能是因為它為查詢中的每個專案回傳了一個列印陳述句,但我無法修復它。
我目前仍在嘗試解決第二個問題,但是對于這兩個問題的任何和所有提示都表示贊賞!
uj5u.com熱心網友回復:
您的查詢將Your query will just return an IQueryable<string> { "london", "london", "london" }因為Select().
您可以簡單地對您的代碼進行 1 次查詢...
var query = db.Customers
.Where(customer => new() {
customer.City,
customer.CompanyName
});
var count = query.Count();
// output: 6
foreach(var customer in query)
{
Console.Writeline(customer.CompanyName);
}
// output:
// Around the Horn
// B's Beverages
// Consolidated Holdings
// Eastern Connection
// North/South
// Seven Seas Imports
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510720.html
標籤:C#林克实体框架核心
