LinQ with graph and where is the condition

Hihi, I have a table with the following data:

SampleID | SampleKey | SampleData 1 | 1 | abc 1 | 2 | def 2 | 1 | xxx 2 | 3 | yyy 3 | 3 | zzz 3 | 4 | qqq 

I would like to get all rows with at least one SampleKey as 3, which should give me

  2 | 1 | xxx 2 | 3 | yyy 3 | 3 | zzz 3 | 4 | qqq 

both SampleIDs 2 and 3 must be returned as they are treated as one pair.

Allowance pls how can i achieve this? Thank you

+4
source share
6 answers

I would suggest not using Contains , but the built-in Join method to improve performance ..

 var keys = source.Where(s => s.SampleKey == 3).Select(s => s.SampleID).Distinct(); var result = source.Join(keys, s => s.SampleID, k => k, (s, k) => s); 
+3
source

Not sure if I fully understand the question, but here is my bet:

 var results = from r in MyTable where r.SampleID == 3 || r.SampleKey == 3 select r; var nResults = results.Count(); 

Although, to be honest, I don’t know why your column named ID is not really an identifier. Nothing, I think I understood it now. You bind these two columns as a unique key (or I hope).

-

EDIT

Nappy really was a great solution , and I'm not sure why he / she deleted it. Capturing all lines from 3 and then reuniting with them works fine.

+1
source

In non-SQL syntax, you can use

 var groupsById = MyData.GroupBy(x => x.SampleId); var groupsThatMatch = groupsById.Where(g => g.Any(x => x.SampleKey == 3)); var allRows = groupsThatMatch.SelectMany(g => g); 

ie by identifier, find the groups that match, then smooth them back into lines. I don't know the syntax like SQL, sorry.

+1
source
  var idsToSelect = from x in MyTable where x.SampleKey == 3 select x.SampleID; var results = from x in MyTable where idsToSelect.Contains(x.SampleID) select x; 
+1
source
  DataTable dt = new System.Data.DataTable(); dt.Columns.Add("SampleID", typeof(Int32)); dt.Columns.Add("SampleKey", typeof(Int32)); dt.Columns.Add("SampleData", typeof(string)); dt.Rows.Add(1, 1, "abc"); dt.Rows.Add(1, 2, "def"); dt.Rows.Add(2, 1, "xxx"); dt.Rows.Add(2, 3, "yyy"); dt.Rows.Add(3, 3, "zzz"); dt.Rows.Add(3, 4, "qqq"); var result = from DataRow myRow in dt.Rows where (int)myRow["SampleID"] == 3 || (int)myRow["SampleKey"] == 3 select myRow; 
0
source

You can probably:

 var result = data.Where( y => data.Where(x => x.SampleKey == 3) .Select(x => x.SampleID) .Contains(y.SampleID)); 
0
source

All Articles