vb.net,linq , check if a list contains all the element in an array using linq

check if a list contains all the element in an array using linq


Tag: vb.net,linq

I have a list of objects and I have an array of keywords. I need to check if all the elements of the array are present inside the list of objects. The user enters the data to be searched like this


My code looks like:

    //i check if the data is present in the list
    Dim keys = str.Split("+")
    dim linqMeddata = From m In medicineDataList
                       Where m.MedicineData.Contains(key(0)) AndAlso m.MedicineData.Contains(key(1)))
                       Order By m.MedicineName Ascending
                       Select m

I need to know how I can check if all the elements of the array are present in the list. Currently I am hard coding the keywords; I need a dynamic solution.


You can use Enumerable.All:

dim linqMeddata = From m In medicineDataList
                  Where keys.All(Function(k) m.MedicineData.Contains(k))
                  Order By m.MedicineName Ascending
                  Select m


Get List of Elements in Tree with specific Field Value

I have an Interface like this: Public Interface TreeSelectorAttributes Property selectedInTreeSelector As Boolean Property Name As String ReadOnly Property childs As IEnumerable(Of TreeSelectorAttributes) End Interface and I have a TreeView which has a List of this TreeSelectorAttributes: Public Property rootList As IEnumerable(Of TreeSelectorAttributes) now after the User chooses which elements...

Updating entity framework model using Linq

I have a problem with updating data in an entity framework model. I have a few tables in the model (Users, UserActivity and Orders). I have added associations between the tables, one between Users and UserActivity and one between Users and Orders. The associations are through the column UserID. These...

orderby () containing numbers and letters

I want to order an array containing numbers and letters in an ascending order the values are stored as a string in a DB. This is the list I have 4B 1A 1 1B 2 4C 4 and want them to order like this where numbers are ascending followed by...

how can i use parameters to avoid sql attacks

I have a project without any parameters used in SQL queries. Is there any solution so that i don't have to change the function and validate parameters from the Query string itself? Query = "select * from tbl_Users where userName='"& textbox1.text &"' and password='"& textbox2.text &"' " ds = obj.ExecuteQueryReturnDS(Query)...

how can I add a column to IQueryable object and modify its values

var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

Visual Basic Datagrid View change row colour

Every other change to the datagrid view works fine but for some reason the row color just wont change. Ive debugged and my application goes through the loop to change the row color. Also I have a button that gives the datagrid view a new list and colors the rows...

Syntax error in Insert query in Mysql in VB.Net

I am doing project in VB.NET and backend is mysql Can you please tell me where the error is occured Public Sub ins() con.Open() Dim cmd1 As New OdbcCommand("insert into party values('" + pcode_txt.Text + "','" + Trim(UCase(name_txt.Text)) + "','" + Trim(UCase(addr_txt.Text)) + "','" + phone_txt.Text + "','" + combo_route.SelectedItem...

ZipEntry() and converting persian filenames

In my vb.net project I'm trying to add a file with a Persian name to a zip file and I do this with the code bellow: Dim myentry As New ZipEntry(dr.Item("MyFile").ToString()) zipOut.PutNextEntry(myentry) however when I open the zip file I see the file name is changed to a gibberish Is...

Can't output Guid Hashcode

I'm trying to use the hashcode of a guid as a random voucher name for a website, and have been trying to write new records to a SQL table with the Hashcode variable but it doesn't work. command.Parameters.Add("@voucherName", SqlDbType.NVarChar) command.Parameters("@voucherName").Value = Guid.NewGuid().GetHashCode() When using that code it just puts a...

Custom drawing using System.Windows.Forms.BorderStyle?

I want to mimick drawing of default border based on value of property BorderStyle. Instead of single border around the control, my control is visualised as four adjacent custom-drawn boxes (2×2), each having standard border drawn individually. So for example, if Control.Border is set to FixedSingle value I want to...

Scraping Javascript webpage (script error occurred)

I am scraping a dynamic webpage which is a javascript based webpage. I have done codes which is used to load the webpage first in the program: Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load WebBrowser1.Navigate("http://www.changiairport.com/flight-info/flight-status/passenger-departures") End Sub However, each time I run the program, script...

Sort Array by contains specific char count

I have an array and I want to sort this array by its element' specific character count. var myNewArray = myArray.ToList().Sort(u => u.Name.Split(' ').Length); but this does not work at all. How can I provide the LINQ code for this problem ? myArray[0] = "word1 word2" myArray[1] = "word1" myArray[2]...

Finding an item in a list in c#

The code below contains a foreach loop that loops through a list of string collection which contains XML. While enumerating through the collection, it reads the question and answer elements and adds them to the list collection. I need to ensure that no repeated question is added to the list...

Adding where clause to IEnumerable Select

I have the following line of code in my controller that selects the id's of the interests shown within a view (they are listed down the page). IEnumerable<int> interestIds = viewModel.ExistingInterests.Select(x => x.InterestId); However I want to be able to add a where clause to the select section. In ExisitingInterests...

Set Label From Thread

Form1.vb Imports System.Threading Public Class Form1 Dim demoThread As Thread Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Start As New Class1 Me.demoThread = New Thread( _ New ThreadStart(AddressOf Start.ThreadProcSafe)) Me.demoThread.Start() End Sub Delegate Sub SetTextCallback([text] As String) Public Sub SetText(ByVal [text] As String) ' InvokeRequired required...

Comparing arrays with numbers in vb.net

I need a way to compare two arrays in vb.net and save result in third array: Dim KonRes(3) As Integer Dim UserRes(3) As Integer Dim YelRed(3) As Integer KonRes(0) = 1 KonRes(1) = 2 KonRes(2) = 3 KonRes(3) = 4 UserRes(0) = 4 UserRes(1) = 3 UserRes(2) = 2 UserRes(3)...

Asp.Net Identity find users not in role

I need to find all users that DONT'T contain a certain role, using Asp.Net Identity. So far I have something like this but it is not working. (From role In context.Roles From userRoles In role.Users Join us In context.Users On us.Id Equals userRoles.UserId Where role.Name <> "SomeRole" Select us.UserName) This...

NullReference Error while assiging values of Modeltype in MVC View (Razor)

I have the following MVC Model: Public Class Employee Public Property EmployeeID As Integer End Class Controller: Namespace Controllers Public Class EmployeeController Inherits Controller Function Details() As ActionResult Dim employee As Employee employee = New Employee employee.EmployeeID = 101 Return View() End Function End Class End Namespace View: @ModelType MVCDemo.Employee...

Filtering Last Duplicate Occurrence In A Datatable

I am sorting a datable with the following code.. Dim sortedExtRecords1 As DataTable sortedExtRecords1 = parsedDataset.Tables("Detail").Clone Dim dvParsedDataset1 As New DataView(parsedDataset.Tables("Detail")) dvParsedDataset1.Sort = AuthorizatonConstants.Authorization_ID sortedExtRecords1 = dvParsedDataset1.ToTable("Detail") I can further filter the results to only return non duplicates and if there is duplicates I want the last record of the...

sqlite query slow, how to optimize (using linq to entities)

I have used MS SQL server a few times and have yet to run into a speed issue when querying, using linq to entities. This time, I am using sqlite, as to ship the entire database with the application. I have a winforms app that contains 4 search fields. My...

Can't access any of Linq methods

I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report...

Load XML to list using LINQ [duplicate]

This question already has an answer here: XDocument to List of object 1 answer I have following XML: <?xml version="1.0" encoding="utf-8"?> <start> <Current CurrentID="5"> <GeoLocations> <GeoLocation id="1" x="78492.61" y="-80973.03" z="-4403.297"/> <GeoLocation id="2" x="78323.57" y="-81994.98" z="-4385.707"/> <GeoLocation id="3" x="78250.57" y="-81994.98" z="-4385.707"/> </GeoLocations> <Vendors> <Vendor id = "1" x="123456" y="456789" z="0234324"/>...

How to make existing forms deriven from a base form in VB.net

I have an existing project in VB.net with many Windows forms.I want to change all forms to deriven from a base form created in a class library. is there any way to do so? if i do inheritance with a code like this the designer dose not show the child...

Retrieve full path of FTP file on drag & drop?

I can read the filename using next code when dragging a file from an Ftp folder browsed on Windows explorer. But is there a way to retrieve the full Ftp path? Private Sub DataGridView1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop Dim filename As String = "" If e.Data.GetDataPresent("UniformResourceLocator") Then...

How do I convert this tSQL statement to LINQ using group by in a sub query

I have the following MSSQL query I am trying to convert to LINQ. I am using entity framework with the following syntax to get at the data. var rv = (from i in DC.TableA select i).ToList(); This is the sql I want to write a C# LINQ query for but...

How to declare var datatype in public scope in c#?

I write simple query with linq to sql : var query = (from p in behzad.GAPERTitles select new { p.id, p.gaptitle }).ToArray(); up code into the c# windows application ,windows form load event,and i want use up result into the button click event in this scope: private void button1_Click(object sender,...

Regex to check if string is alphanumeric separated by commas or a single alphanumeric string

I have the following right now which works fine if the string is alphanumeric and separated by commas, but it doesn't work if I only have a single string. "^([a-zA-Z0-9]+,)+[a-zA-Z0-9]+$" Works for something like "1A,1B,1C", doesn't work on "1A" Sorry, I don't know much about regex and I only got...

Connecting to database using Windows Athentication

I would like to use window authentication in my program to connect to my sql server. users already have certain permissions on the SQL server and I would like to leverage that in my program. The way I currently connect to the server is using this connection string. Dim ConnectionString...

Compare if the characters in a string are a subset of a second string in C#

I'm working on a game where I want to check if the characters of a string are contained in another string. Obviously a set would be my first choice but I want to account for duplicates. For example: "met".IsContainedWithin("meet"); => true "meet".IsContainedWithin("met"); => false A multi-set would be nice but...

Update list of items in c#

I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...

How do I use VB.NET to send an email from an Outlook account?

I'm trying to send an email via an outlook email account through a vb.net program. When I run the code I get an error telling me that I don't have a secure connection. I've been searching online and have tried all the adjustments I've found but I'm still not having...

Convert Double from String

When converting string to floating, the converter creates wrong results. ?Global.System.Convert.ToDouble("635705821821928755").ToString("0") "635705821821929000" ?Global.System.Convert.ToSingle("635705821821928755").ToString("0") "635705800000000000" I am working with VB.Net Visual Studio 2012, Framework 4 on ASP.Net Webpage. Is there any solution for converting huge numbers from string into floating?...

Removing Alert When Using DeleteFile API

I'm writing a VBA application which involves looping a large number of directories recursively. I am using the FindFirstFile API to to achieve this, as it offers a substantial performance boost over the FileSystemObject. In order to remove the FSO from my code entirely, I need a routine to delete...

Distinct all columns in a datatable and store to another datatable with LINQ

I have a datatable with more than 10 columns and I would like to distinct all columns and then store a result to another datatable. Is there any way to distinct all columns in a datatable by using LINQ without naming all ones? I've tried as the code below but...

Return index of word in string

This code: Module Module1 Sub Main() ' Our input string. Dim animals As String = "cat, dog, bird" ' See if dog is contained in the string. If Not animals.IndexOf("dog") = -1 Then Console.WriteLine(animals.IndexOf("dog")) End If End Sub End Module Return start position 5 in string But how to return...

How to pass all value of ListBox Control to a function?

I am writing a simple application to read the value a textbox and add to a listbox control . But i have to pass the listbox control to function . Any suggestion ? Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load test("E:\Satyajit.txt") End Sub Public Function...

VB.Net DateTime conversion

I have a jquery datepicker in a usercontrol. On the usercontrol i have a property that will return the selected date to the page which contains my usercontrol. I try to convert the string to a date: Dim MyDate As System.DateTime = System.Convert.ToDateTime(txtFromDateF.Value, System.Globalization.DateTimeFormatInfo.InvariantInfo) i keep getting the error: String...

check if a list contains all the element in an array using linq

I have a list of objects and I have an array of keywords. I need to check if all the elements of the array are present inside the list of objects. The user enters the data to be searched like this pain+fever+thirst+itching My code looks like: //i check if the...

Linq update with specific select of column being null

I wanted to select few columns from SQl and then update that table. I used var xyz_repl= from mfrepl in xyz_repl_alias where (mfrepl.RPT_ID == sched_data.NOTIF_RPT_ID) && (mfrepl.NOTIF_ID == "" || mfrepl.NOTIF_ID == null) select mfrepl; This did my job but then it does not work if any column is NULL.Then...

Automapper AfterMap function initialising classes

Can anyone please explain how does the AfterMap function initalises the class objects passed in the lambda expression? When i run this bit of code as myself, it populates the dest object with my details. i can't figure out how is it doing that? but if someone can tell me...

Convert date to string format

I have successfully imported data from xls into dataGridView. The date column in dataGridView is showing the DateTime format. I want this date column to be displayed in "dd MMM yyyy" format. I have tried as shown below: connExcel.Open() Dim dtExcelSchema As DataTable dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing) Dim SheetName As...

How does the Take() method work in LINQ

I have a question regarding LINQ's Take() Method. I have a somewhat large table I'm querying in my web app, and I only want to return say N number of rows from the table. I've read through the MSDN documentation, but I can't see where it states if Take() first...

Linq Conditional DefaultIfEmpty query filter

I have a query as below: bool variable = false//or true var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user = u, profile = p }; This...

Get XML node value when previous node value conditions are true (without looping)

Sample XML - <?xml version="1.0"?> <Root> <PhoneType dataType="string"> <Value>CELL</Value> </PhoneType> <PhonePrimaryYn dataType="string"> <Value>Y</Value> </PhonePrimaryYn> <PhoneNumber dataType="string"> <Value>555-555-5554</Value> </PhoneNumber> <PhonePrimaryYn dataType="string"> <Value>Y</Value> </PhonePrimaryYn> <PhoneType dataType="string"> <Value>HOME</Value> </PhoneType>...

How to select all objects that have a property value in list of values?

I have a table named Items. Items have a property named "locationId" Given a list of location Ids, how do I select all items? List example List<long> locationIds = new List<long> { 1, 2, 3 }; Essentially the query below, but for multiple locations at once: var sleectedItems= db.Items.Select(i =>...

Gridview items not populating correctly

I have data I am trying to input into a gridview. I am looking up the number of rows for the gridview and adding data into them like this: My "test" however does not get populated into the Submitted and Variance BoundFields in the Gridview. All that populates is the...

Error when building an XDocument

Using the following example xml containing one duplicate: <Persons> <Person> <PersonID>7506</PersonID> <Forename>K</Forename> <Surname>Seddon</Surname> <ChosenName /> <MiddleName /> <LegalSurname /> <Gender>Male</Gender> </Person> <Person> <PersonID>6914</PersonID> <Forename>Clark</Forename> <Surname>Kent</Surname> <ChosenName>Clark</ChosenName> <MiddleName />...

Please help me convert this sql to LINQ

DECLARE @items table ( pfid varchar(8), timestart datetime, timeend datetime ) insert INTO @items(pfid,timestart,timeend) VALUES('123456','12:00 AM','3:00 AM') ,('987654', '2:00 AM', '4:00 PM') ,('492384', '3:00 PM', '9:00 PM') SELECT * FROM @items a INNER JOIN @items b ON a.timestart < b.timeend AND b.timestart < a.timeend AND a.pfid != b.pfid I need...