Improve company productivity with a Business Account.Sign Up

x

LINQ Query

554

Solutions

404

Contributors

Language Integrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, although ports exist for Java, PHP, JavaScript and ActionScript. LINQ extends the language by the addition of query expressions, which are akin to SQL statements, and can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases, and third-party data sources.

Share tech news, updates, or what's on your mind.

Sign up to Post

string SpeSubject = "ENGLISH"
List<string> SubjectAll = new List<string>() { "PHYSICS=100", "MATHS=100", "ENGLISH=99", "CHEMISTRY=97", "BIOLOGY=96" };

string[] Result = SubjectAll.Where(str => SpeSubject.Any(str1 => str.Contains(str1))).ToArray();

How to fetch the Matching values from SubjectAll.

For Example, My searchstring is ==> SpeSubject = "English"

I want to search this field ("ENGLISH") in SubjectAll list and return as "ENGLISH=100"

i written the query below. But, it will fetch only the first records.

How to fetch the exact record..?



string SpeSubject = "ENGLISH"
List<string> SubjectAll = new List<string>() { "PHYSICS=100", "MATHS=100", "ENGLISH=99", "CHEMISTRY=97", "BIOLOGY=96" };

string[] Result = SubjectAll.Where(str => SpeSubject.Any(str1 => str.Contains(str1))).ToArray();

Finally i want to store English and Marks are seperate.


string ColumnName = Result.Select(str2 => str2.Split('=')[0]).FirstOrDefault();  

string ColumnValue = Result.Select(str2 => str2.Split('=')[1]).FirstOrDefault());

my final value should be as

ColumnName = ENGLISH
ColumnValue = 99

where we need to change the code...?
0
Get expert help—faster!
LVL 12
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

I need to know how to write a ForEach Loop to find a string value that correlates to an integer. Is this possible?

ForEach ID in StringField
  Do Something
0
Hello Friends,
I have a chart which i have built using the linq query which is as below
 
public List<DatewiseStockDetailViewModel> getProductSoldByYear(int CompanyId)
{
var userData = (from m in datewise.GetAll()
join s in stock.GetAll()
on m.Stock_Id equals s.Stock_Id
join p in product.GetAll()
on s.ProductId equals p.ProductId
where s.CompanyId == CompanyId && m.IsProductDeducted == true
group new { m, s, p } by new { Convert.ToDateTime(m.CreatedDate.ToString()).Year, p.ProductName, p.ProductId } into g
select new DatewiseStockDetailViewModel
{
productId = Convert.ToInt32(g.Key.ProductId),
productName = g.Key.ProductName,
ProductQuantity = g.Sum(x => x.m.ProductQuantity),
year = g.Key.Year.ToString()
}).Distinct().ToList<DatewiseStockDetailViewModel>();
return userData;
}

Open in new window


This is the current output which i am getting
But i want to write a code by which i am able to use the pivot code in linq to get the output as
ProductName         2016         2017         2018
cedar oil                  NULL        16         34
computer                 NULL         8               1
grain                        NULL   21       NULL
Keyboard                  2           3       NULL
marie                        NULL        26     NULL
Pine Oil                     NULL         4                  5
harabhara kebab      NULL            5               1
 
For this i have written the sql query
 
select *
from(
select pd.ProductName,year(dsm.CreatedDate)as [Year],sum(dsm.ProductQuantity)as ProductQuantity
from dbo.DatewiseStockDetailMaster dsm
left join dbo.StockMaster sm on
dsm.stock_Id=sm.stock_Id
left join dbo.ProductDetails pd
on sm.ProductId=pd.ProductId
where sm.CompanyId=17 and dsm.IsProductDeducted=1
group by year(dsm.CreatedDate),pd.ProductName
)as SourceTable
pivot
(
sum(ProductQuantity)
for [Year]
in([2016],[2017],[2018])
)
as pivotTable

Open in new window


How to convert from sql to linq using pivot
0
The codes below is working ok. I just need to make VAR response to be sorted.
How can I do that?

   public static List<Make> GetVehicleMakeList()
        {
            List<Make> lstMake = new List<Make>();
            HttpClient objClient = new HttpClient();
            try
            {
                var response = objClient.GetStringAsync(Utility.Enumeration.vehicleMakeAPICall).Result;
                if (!string.IsNullOrEmpty(response))
                {
                    VehicleMakeAPIResponse objMakeResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<VehicleMakeAPIResponse>(response);
                    return objMakeResponse.Results;
                }

            }
            catch (Exception ex)
            {

                //log error message here
            }
            return lstMake;
        }

Open in new window

0
This is fragment of my .cs code

        public arAbonamenty_page()
        {
            InitializeComponent();
 

            Nexo_ARWALEntities myNexo_ARWALEntities = new Nexo_ARWALEntities();

            Nullable<Int32> grupa_tw = new Nullable<Int32>();
            grupa_tw = null;
            short? kiedy_fakturować_combo = new Nullable<Int16>();
            bool? bool_okres_płatności = new Nullable<bool>();
            if (okres_płatności.SelectedIndex == 2)
            {
                bool_okres_płatności = null;
            }
            else
                bool_okres_płatności = Convert.ToBoolean(okres_płatności.SelectedIndex);

            Nullable<bool> kiedy_fakturować = new Nullable<bool>();
            kiedy_fakturować = Convert.ToBoolean(kiedy_fakturować_combo);

            var query = (from myabonamenty in myNexo_ARWALEntities.ArAbonamenty
                         join nexotowary in myNexo_ARWALEntities.Asortymenty
                         on myabonamenty.nexo_towar equals nexotowary.Id
                         join myklienci in myNexo_ARWALEntities.ArKlienci
                         on myabonamenty.id_klient equals myklienci.id_klient
                         where (grupa_tw == null || (grupa_tw != null && nexotowary.Grupa_Id == grupa_tw))
                         where (myabonamenty.czy_fa_auto_na_początku_okresu == null || (kiedy_fakturować != null && myabonamenty.czy_fa_auto_na_początku_okresu == kiedy_fakturować))

                         

Open in new window

0
1. How can get the list (element (State)))  filter by state if parameter is given e.g. (CA) order by State asc?
2. How can get the list (element (Name)) filter by Status = Online and state = "CA" order by Name asc?

3. How can get total count of Bond filer by state?
4. How can get total count of Bond filter by Status (e.g. Online)?

I would like to see in c#.

Thanks,


<Surety>
<SuretyLine>
<Commercial>
<Bond>
        <GeneralInformation UI="BondInfo">
          <Name ID="bondName" PrefillValue="Yes">C</Name>
          <State ID="bondState" PrefillValue="Yes">CA</State>         
        </GeneralInformation>              
        <Status>Online</Status>
</Bond>
<Bond>
        <GeneralInformation UI="BondInfo">
          <Name ID="bondName" PrefillValue="Yes">Z</Name>
          <State ID="bondState" PrefillValue="Yes">CA</State>         
        </GeneralInformation>              
        <Status>Online</Status>
</Bond>
<Bond>
        <GeneralInformation UI="BondInfo">
          <Name ID="bondName" PrefillValue="Yes">B</Name>
          <State ID="bondState" PrefillValue="Yes">FL</State>         
        </GeneralInformation>              
        <Status>Online</Status>
</Bond>
</Commercial>
</SuretyLine>
</Surety>

Open in new window

0
Hi,
I need to create a report in SharePoint 2013 , on premises , There is a custom SharePoint list which has username, Manager and Status. say it SPLIst
I have created another SharePoint list as external content type using SQL procedure which returns all all active users. In this second list say DBList I have username and their department.
My requirement is , I need to compare the two lists and whoever is not found in SPList, should be marked as "Not Started".

Could you please help me to achieve this?

Thanks in advance.
Azra
0
I have been tasked with adding some very specific searching behaviour to a MVC application using Entity Framework.  

The searching should be able to get:

Entries with two or more words that are not just exactly next to each other. If they type in "The Revenge":
  • The Revenge
  • The Horrible Revenge
  • Revenge of the Machines

Parts of words. If they type in "Smith":
  • Mr and Mrs Smith
  • Meet the Smithsons
  • The Incredible Blacksmith

I have written the following method in my controller class:

public ActionResult Index(string searchString)
        {

            var films = from s in db.films
                        select s;

            if (!string.IsNullOrEmpty(searchString) && !searchString.Any(x => Char.IsWhiteSpace(x)))
            {
                searchString.Trim();
                films = films.Where(s => s.title.Contains(searchString)
                    || s.title.StartsWith(searchString)
                    || s.title.EndsWith(searchString)
                    || s.genre.Contains(searchString)
                    || s.genre.StartsWith(searchString)
                    || s.genre.EndsWith(searchString)
                    || s.synopsis.Contains(searchString)
                    || s.synopsis.StartsWith(searchString)
                    || s.synopsis.EndsWith(searchString)
            }
      

Open in new window

0
Hi Experts,
I need help setting a default value to 0, when the returned value is null, or 0.
I have tried the code below but I get a blank\empty field in my table.  See code below, and let me what I am doing wrong.

CODE
var paper = (db.Manifests.Where(m => m.ID == ID && m.ProcessedDate.Value.Month == DateTime.Today.Month).Sum(m => m.Claims != null  ? m.Claims : 0)).Value;
vals.Add((paper.ToString().Length > 0) ? string.Format("{0:###,###}", paper) : "0");

Open in new window



Thank you,
mrotor
0
how to get coming expires before 7 month  in linq
0
Free Tool: Site Down Detector
LVL 12
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I have BPM (Method Directive) in Epicor 10.1.600.

BO:  JobEntry

Method:  ChangeJobHeadProdTeamID

The user trigger its from the Job Entry screen by changing the "Prod Team" field.  The BPM has a Post-Processing directive, which looks like this:
foreach (var ttJobHead_Row in ttJobHead)  //ttJobHead
{
  using (var txScope = IceContext.CreateDefaultTransactionScope())
  {
    //get the header row and update it
    var jobheadrow = (from JobHead_Row in Db.JobHead.With(LockHint.UpdLock)
                      where JobHead_Row.Company == ttJobHead_Row.Company
                      && string.Compare(JobHead_Row.JobNum, ttJobHead_Row.JobNum, true) == 0
                      select JobHead_Row).FirstOrDefault();
               
               if (jobheadrow != null)
               {
                 jobheadrow.Serial_c = callContextBpmData.Character01;
                 jobheadrow.Height_c = Convert.ToInt32(callContextBpmData.Number01);
                 jobheadrow.Width_c = Convert.ToInt32(callContextBpmData.Number02);
                 jobheadrow.PaintColor_c = callContextBpmData.Character02;
                 
               } 
      
    }
    
    Db.Validate();
    txScope.Complete();    

  }
   
}

Open in new window


It executes successfully, and brings me back to the Job Entry screen.  When I select "Save" on the Job Entry screen, I get the error:
error
I have tried putting in:
var jobEntryBO = Ice.Assemblies.ServiceRenderer.GetService<Erp.Contracts.JobEntrySvcContract>();
var currentJob = jobEntryBO.GetByID(ttJobHead_Row.JobNum);
this.dsHolder.Attach(currentJob);

Open in new window


before the line:
txScope.Complete();

But still receive the error.  Would you know what is wrong here?
0
Below codes is to call Twilio API and get the sms historical conversation for one phone no. However, it takes over 15 seconds and the total records is actually just 5 conversation.

Have any experts worked with Twilio in the past and know another way to get SMS conversation in a faster mode?
Thanks,



TwilioClient.Init(accountSid, authToken);
            var messages2 = MessageResource.Read().Where(x => x.From.ToString() == fromPhoneNo);
            var messages3 = MessageResource.Read().Where(y => y.To == fromPhoneNo);
            var all = messages2.Concat(messages3).OrderByDescending(z => z.DateCreated);

Open in new window

0
I need to get a random record from  sql database with Linq query in entity.
0
I trying to create a query similar to below.    

I want a list of opportunities by FKVCCenterID.  But I have to go right back to the organisation and then to the VCCentres get this.

VCCentres have Organisations
Organisations have Opportunities


This query works except it returns an aynonmous type instead of the type i want which is tblOpportunities

  var opportunities = (from org in _ctx.tblVCCenterOrganisations
                join vc in _ctx.tblOrganisations on org.FKOrganisationID equals vc.OrganisationID
                join ops in _ctx.tblOpportunities on org.FKOrganisationID equals ops.FKOrganisationID
                select new
                {
                    FKVCCenterID = org.FKVCCenterID,
                    OpportunityID = ops.OpportunityID,
                    Title = ops.Title,

                }
            ).Where(x => x.FKVCCenterID == 999).Take(take).Skip(skip);


If i specify the type "select new tblOpportunity()" the where clause breaks because the tblOpportunity does not contain the FKVCCenterID
  var opportunities = (from org in _ctx.tblVCCenterOrganisations
                join vc in _ctx.tblOrganisations on org.FKOrganisationID equals vc.OrganisationID
                join ops in _ctx.tblOpportunities on org.FKOrganisationID equals ops.FKOrganisationID
                select new tblOpportunity()
                {
                    OpportunityID = ops.OpportunityID,
                    Title = ops.Title,

    …
0

LINQ Query

554

Solutions

404

Contributors

Language Integrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, although ports exist for Java, PHP, JavaScript and ActionScript. LINQ extends the language by the addition of query expressions, which are akin to SQL statements, and can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases, and third-party data sources.

Top Experts In
LINQ Query
<
Monthly
>