Get full rows based on single column distinct - linq

Actually I want to get the full table but it should be based on Doc_Type==distinct
Means it should only pick the records from table that has unique Doc_Type. I have tried with following but it returns me a single column into tolist() but I want to get full table. How can I do it?
var data = DB.tblDocumentTypes.Select(m => m.Doc_Type).Distinct().ToList();

You can use GroupBy
var data = DB.tblDocumentTypes.GroupBy(m => m.Doc_Type).Select(x => x.First());

Related

How to match exact Id within Comma seperated database column using LINQ and Lambda

Hi I have SQL Table where I am storing values like this:
Column Name: Registration_ID
180,1801,1803,18011,220
180,1801,
180,1801,1803
No I want to match exact Registration_ID and get records based on the Registration_ID. I have tried Contains but is not matching exact values.
Here is my query:
var Result=db.Entity_StudentRepository.Get(x =>
x.Registration_ID.Contains(Used_For_Id.ToString())).Select(x => x.Registration_ID).ToArray();
Could you please try the following query and let know if it works-
db.Entity_StudentRepository.AsEnumerable().Where(t=> Registration_ID.Split(',').Select(int.Parse).Contains(Used_For_Id));

.Where in LinQ not working correctly

I have Documents table and Signs table. Document record can be related with many records in Signs table.
Now, I want to get all records of Documents table when document ID appears in Signs table.
Here I get all documents:
var documents = (from c in context.documents select c);
Here I get all my signs and save into List:
var myDocuments = (from s in context.signs where s.UserId== id select s.ID).ToList();
This list contains collection on document ID.
And here, I'm trying to get all documents that exists in myDocuments list:
documents.Where(item => myDocuments.Contains(item.ID));
But, when I do .ToList() allways return all records (in database only exists one compatible record)
What is wrong in LinQ statement?
The problem is that this statement doesn't modify the contents of documents, it merely returns the results (which you're not doing anything with):
documents.Where(item => myDocuments.Contains(item.ID));
documents is still the full list.
Change this line to something like:
var matchingIDDocs = documents.Where(item => myDocuments.Contains(item.ID));
And then use matchingIDDocs in place of "documents" later in your code.

How do I get unique Linq-to-Entities results when there is no primary key?

I have an entity model of an Oracle data source over which I have no control. Using this model I query a particular view to see get all volume price breaks for a given product:
As you can see, this view has no primary key. Here is the LINQ I am using:
var db = GetOracleDataContext();
var result = db.ITEMPRICEBREAKS_V.Where(p => p.STOCKNO == stockId).ToList();
This works to some degree, but instead of returning four distinct records with their own quantities and pricing, it returns four identical records, each with the pricing and quantities of the first record ($4800, 0, 2).
I have no control over this view. Is there another way I can structure my LINQ query so that I can get the four distinct values?
Select only the fields you care about and use Distinct(). For example:
var result = db.ITEMPRICEBREAKS_V
.Where(p => p.STOCKNO == stockId)
.Select(p => p.Price)
.Distinct()
.ToList();
However, I'd strongly recommend, along with the other commenters, that you get a primary key involved.

Finding items from a list in an array stored in a DB field

I have a legacy database that has data elements stored as a comma delimited list in a single database field. (I didn't design that, I'm just stuck with it.)
I have a list of strings that I would like to match to any of the individual values in the "array" in the DB field and am not sure how to do this in Linq.
My list:
List<string> items= new List<string>();
items.Add("Item1");
items.Add("Item2");
The DB field "Products" would contain data something like:
"Item1,Item3,Item4"
"Item3,Item5,Item6"
"Item2,Item7,Item6"
"Item1,Item2"
"Item1"
My first pass at the Linq query was:
var results = (from o in Order
.Where(p=> items.Contains(p.Products)
But I know that won't work. because it will only return the records that contain only "Item1" or "Item2". So with the example data above it would return 0 records. I need to have it return two records.
Any suggestions?
There is a simple clever trick for searching comma-separated lists. First, add an extra , to the beginning and end of the target value (the product list), and the search value. Then search for that exact string. So for example, you would search ,Item1,Item3,Item4, for ,Item1,. The purpose of this is to prevent false positives, i.e., Item12,Item3 finding a match for Item1, while allowing items at the beginning/end of the list to be properly found.
Then, you can use the LINQ .Any method to check that any item in your list is a match to the product list, like the following:
var results = (from o in Order
.Where(o => items.Any(i => (","+o.Products+",").Contains(","+i+",")))
One way would be to parse the list in the Products field:
var results = (from o in Order
.Where(o => items.Any(i => o.Products.Split(',').Contains(i))
But that would parse the string multiple times for each record. You could try pulling back ALL of the records, parsing each record once, then doing the comparison:
var results = from o in Order
let prods = o.Products.Split(',')
where items.Any(i => prods.Contains(i))
select o;

Sequel Migration update with a row's ID

How can you run a Sequel migration that updates a newly added column with a value from the row?
The Sequel documentation shows how you can update the column with a static value:
self[:artists].update(:location=>'Sacramento')
What I need to do is update the new column with the value of the ID column:
something like:
self[:artists].each |artist| do
artist.update(:location => artist[:id])
end
But the above doesn't work and I have been unable to figure out how to get it to go.
Thanks!
artist in your loop is a Hash, so you are calling Hash#update, which just updates the Hash instance, it doesn't modify the database. That's why your loop doesn't appear to do anything.
I could explain how to make the loop work (using all instead of each and updating a dataset restricted to the matching primary key value), but since you are just assigning the value of one column to the value of another column for all rows, you can just do:
self[:artists].update(:location=>:id)
if you need update all rows of a table, because it is a new column that need be populate
artists = DB[:artists]
artists.update(:column_name => 'new value')
or if you need, update only a unique row into your migration file you can:
artists = DB[:artists]
artists.where(:id => 1).update(:column_name1 => 'new value1', :column_name2 => "other")

Resources