Home > OS >  Filtering using LINQ
Filtering using LINQ

Time:03-09

I have a telephone number (string) which is "98574524521322". I need to know which country this telephone number belongs to by looking at the country code.

I have 2 tables which are TelephoneMerchant and TelephoneCode. Note: One telephone merchant can have multiple Telephone Codes. Note: The first 2 or 4 digits in the telephone number is the telephone Code, found in the TelephoneCodes table.

Question: I want to write a LINQ query to check who the telephone merchant is for the telephone number "98574524521322" ? My workings:

_dbContext.TelephoneCodes.Where(c => c.Code.ToString().StartsWith("")).FirstOrDefault(c=> c.MerchantName);

The above query doesn't work as I am not sure how to use StartsWith (Or if StartsWith is the right method to use).

The files are given below. Can someone help me how to resolve this ?

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

How the tables look like

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

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

CodePudding user response:

This should work:

string phoneNumber = "98574524521322";
IEnumerable<string> matchingMerchants = _dbContext.TelephoneCodes
    .Where(c => phoneNumber.StartsWith(c.Code.ToString()))
    .Select(c=> c.TelephoneMerchant?.MerchantName)
    .ToList();

Now you have all in a list. If you really just want a single, you can also use:

string matchingMerchant = _dbContext.TelephoneCodes
    .FirstOrDefault(c => phoneNumber.StartsWith(c.Code.ToString())?.TelephoneMerchant?.MerchantName;

But i would really save Code in a String.

  • Related