我有一個電話號碼(字串),它是“98574524521322”。我需要通過查看國家代碼來知道這個電話號碼屬于哪個國家。
我有 2 張桌子,它們是TelephoneMerchant和TelephoneCode。注意:一個電話商可以有多個電話代碼。注意:電話號碼的前 2 或 4 位數字是電話號碼Code,TelephoneCodes見表。
問題:我想撰寫一個 LINQ 查詢來檢查telephone merchant電話號碼“98574524521322”的是誰?我的作業:
_dbContext.TelephoneCodes.Where(c => c.Code.ToString().StartsWith("")).FirstOrDefault(c=> c.MerchantName);
上面的查詢不起作用,因為我不確定如何使用StartsWith(或者是否StartsWith是正確的使用方法)。
檔案如下。有人可以幫我解決這個問題嗎?
public class TelephoneCode: Entity
{
public int Code { get; set; }
public int TelephoneMerchantId { get; set; }
public TelephoneMerchant? TelephoneMerchant{ get; set; }
}
public class TelephoneMerchant: Entity
{
public string? MerchantName { get; set; }
public ICollection<TelephoneCode> TelephoneCodes { get; set; }
}
桌子的樣子
Id TelephoneMerchant MerchantName
===================================
1 ABC ABCMErchant
2 BBB BBB MErcrchat
Id Code TelephoneMerchantId
==================================
1 10 1
2 98 1
3 1023 2
uj5u.com熱心網友回復:
這應該有效:
string phoneNumber = "98574524521322";
IEnumerable<string> matchingMerchants = _dbContext.TelephoneCodes
.Where(c => phoneNumber.StartsWith(c.Code.ToString()))
.Select(c=> c.TelephoneMerchant?.MerchantName)
.ToList();
現在你所有的都在一個串列中。如果你真的只想要一個,你也可以使用:
string matchingMerchant = _dbContext.TelephoneCodes
.FirstOrDefault(c => phoneNumber.StartsWith(c.Code.ToString())?.TelephoneMerchant?.MerchantName;
但我真的會保存Code在一個String.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442860.html
下一篇:將for回圈轉換為linq
