使用 LINQ 过滤

Filtering using LINQ

我有一个电话号码(字符串)是“98574524521322”。我需要通过查看国家代码来知道这个电话号码属于哪个国家。

我有 2 个 table,分别是 TelephoneMerchantTelephoneCode。 注意:一个电话商户可以有多个电话代码。 注意:电话号码的前2或4位是电话Code,在TelephoneCodes table.

中找到

问题:我想编写一个 LINQ 查询来检查电话号码“98574524521322”的 telephone merchant 是谁? 我的工作:

_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; }
}

table 的样子

Id TelephoneMerchant   MerchantName 
===================================
1   ABC                ABCMErchant
2   BBB                BBB MErcrchat

Id   Code    TelephoneMerchantId 
==================================
1    10       1
2    98       1
3    1023     2

这应该有效:

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;

但我真的会在 String 中保存 Code