LINQ Query

581

Solutions

421

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

Hi

I need to improve the performance of the some code

To give you an overview, I have an image which is 320px 240px, each pixel has temperature data associated with it
I've loaded the temperature data into a float[,]:

xytArray:
Float[320,240] - its contains x y pixel position data, and a temperature value
i.e.
[0,0] 70
[0,1] 70
[0,2] 75
etc
Capture.PNG

Then i have many RegionOfInterests which is a list of x y points, this does not contain temperature data, but i do need to use these x y points to look up the current temperature value.
 public IList<Point> RoiPointsList 

Open in new window

Capture.PNG

When i'm Foreaching through the Float[,] i'm adding the temperature data to it
This is fast, and no problem here

However, when i try and check if the RegionOfInterest has a x,y pixel for the current iteration (so i can get its temperature value), it really slows down (i'm checking 12 region of interest of each pixel in loop)
I need a much faster way to check if the RegionOfInterest has a mentioned pixel for the current x,y
Then after building the x, y RegionOfInterest with temperature data, i need to query if for min, max and mean data.


Here is the code

//make an empty float[320,240]
var xytArray = new Single[flirImage.ThermalData.Max(xy => xy.X) + 1, flirImage.ThermalData.Max(xy => xy.Y) + 1];

//populate float[,]
foreach (var xyItem in flirImage.ThermalData) // 76800 rows in flirImage.ThermalData
            {

   

Open in new window

0
Exploring SharePoint 2016
LVL 12
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

I have created a LINQ to return data from SQL server in JSON format which contains nested values.
Attach the code and output, the JSON is showing duplicate values for FieldID:6

var query =  from g in entity.ConfigSearchFieldGroupings
                         join f in entity.ConfigSearchFieldGroupingFields
                         on g.GroupingID equals f.GroupingID
                         join d in entity.ConfigDataFields
                         on f.FieldID equals d.FieldID
                         join ss in entity.ConfigSelections
                         on d.FieldID equals ss.FieldID into t
                         from rt in t.DefaultIfEmpty()
                         join s in entity.ConfigSourceSystems
                         on d.SystemCode equals s.SystemCode
                         where g.IsActive == true
                         && d.IsActive == true
                         && s.IsActive == true
                         && g.GroupingID == siGroupingID
                         && d.IsSearchable == true
                         select new
                         {
                             g.GroupingName,
                             f.FieldID,
                             d.FieldName,
                             d.FieldText,
                             d.FieldDescription,
                             d.FieldCategory,
                             d.FieldDataType,
                             d.FieldLength,
                             

Open in new window

0
I wrote an app that uses
List<string> str = new List<string>();

Open in new window

Problem I have is I'm adding to many items to the string which is causing issues.

I perform a search in the string
var found = (from r in str
             where r == value
             select r);

Open in new window

List<string> can be replaced with a StringBuilder.  

Can you query a StringBuilder with Linq?
0
I have the following query in linq
   var lastPosRaw = (from lp in db.tblCommonTrackingDatas
                                              where lp.vpkDeviceID == deviceid && lp.vReportID == 124 && lp.dGPSDateTime <= positionDateTime
                                              orderby lp.dGPSDateTime descending
                                              select new
                                              {
                                                  vLatitude = lp.vLatitude,
                                                  vLongitude = lp.vLongitude,
                                                  vTextMessage = lp.vTextMessage
                                              });

                            var lastPos = lastPosRaw.Select(a => new Last_Location
                            {

                                vLatitude = long.Parse(a.vLatitude),
                                vLongitude = long.Parse(a.vLongitude),
                                vTextMessage = a.vTextMessage

                            }).FirstOrDefault();



                            if (lastPos != null)
                            {//do stuff}

Open in new window


It seems to be taking time, and on closer inspection, it seems to be returning lots of rows from the DB then selecting the top 1
I need it to  return the first row only, however when i do this

 var lastPosRaw = (from lp in db.tblCommonTrackingDatas
                                              where lp.vpkDeviceID == deviceid && lp.vReportID == 124 && lp.dGPSDateTime <= positionDateTime
                                              orderby lp.dGPSDateTime descending
                                              select new
                                              {
                                                  vLatitude = lp.vLatitude,
                                                  vLongitude = lp.vLongitude,
                                                  vTextMessage = lp.vTextMessage
                                              }).FirstOrDefault();

Open in new window



the line below errors on the SELELCT word

var lastPos = lastPosRaw.Select(a => new Last_Location

Open in new window


'<anonymous type: string vLatitude, string vLongitude, string vTextMessage>' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type '<anonymous type: string vLatitude, string vLongitude, string vTextMessage>' could be found (are you missing a using directive or an assembly reference?)

Any ideas?
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
CompTIA Network+
LVL 12
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

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

581

Solutions

421

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
>