I have a 1 row DataTable that I'd like to convert to the following format:
Column1Name : value
Column2Name : value
Column3Name : value
etc...
How can this be accomplished with LINQ??
Thanks!
How about something like:
DataTable table = ...
// Overlays the columns over the only row's items
// and combines each column-item pair as required.
var items = table.Columns
.Cast<DataColumn>()
.Zip(table.AsEnumerable().Single().ItemArray,
(column, value) => column.ColumnName + " : " + value);
var result = string.Join(Environment.NewLine, items);
Here's another (IMO better) approach:
// Uses the DataRow's column-indexer to match a column with
// the corresponding row-item.
var items = from DataColumn column in table.Columns
select column.ColumnName + " : " + table.Rows[0][column];
var result = string.Join(Environment.NewLine, items);
Related
How can I make a drop-down list from several lists with a condition from another drop-down list?
Using my image above, let's say I on the first drop-down list (this one is a simple one) select "Furniture"... I would like the second drop-down list to only show the furniture. Same thing with the third drop-down list, would like only the color of my second choice to be shown there.
Did try to place on the criteria "Custom formula" in the "Data validation" one of this two formulas but does not work...
=FILTER(Object,Type = E2)
or
=QUERY(A:C,"SELECT B WHERE A='"&E2&"' ", 0)
Did read in some other topic here that it was not possible with formulas and I could not find an app script for it. How can i place conditional rules and make only appear the values i want on the drop-down menu instead all of them ? I think it has something to do with the "withCriteria(criteria, args)" however i am not understanding how to apply it.
About the list ... it will be compose maybe with 2k lines (each line 3 columns). First column will only have (maybe) 6 or 7 different values. Second about 70 or 80 and third all different. The order will be random cause new values could be added and i can be adding a new Furniture or Animal ...
This is the code i have now
function onEdit(e) {
var range = e.range;
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
if ( range.getRow() > 1) {
if ( range.getColumn() == 5) {
var cell_Range = ss.getRange( range.getRow(), range.getColumn() + 1);
var cell = cell_Range.getCell( 1, 1);
var rangeV = SpreadsheetApp.getActive().getRange('B2:B13');
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(rangeV).build();
cell.setDataValidation(rule);
}
else if ( range.getColumn() == 6 ) {
var cell_Range = ss.getRange( range.getRow(), range.getColumn() + 1);
var cell = cell_Range.getCell( 1, 1);
var rangeV = SpreadsheetApp.getActive().getRange('C2:C13');
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(rangeV).build();
cell.setDataValidation(rule);
}
}
}
Example sheet at https://docs.google.com/spreadsheets/d/1aLpYd8fC0jpwvQOPVTj_yvY7DVKeFFnPvpJSF27if6w/edit?usp=sharing
Thanks in advance
Solution:
Use Datavalidation requireValueInList
Flow:
Get All options A1:C as a array
Filter A(Col1) if edited value in E(Col5) is present in it
Retrieve corresponding Col2(B) as options and build data validation based on it
Offset the edited range by 1 column and set DataValidation
Sample Script:
function onEdit(e) {
const SETTINGS = {
//Edited Column : Column to Check(First col in optionsDataRange is considered 1)
5: 1,
6: 2,
};
var editedRange = e.range,
editedSheet = editedRange.getSheet(),
val = e.value,
col = editedRange.columnStart,
row = editedRange.rowStart;
/*Exit clause(s)*/
if (
Object.keys(SETTINGS).indexOf(col.toString()) === -1 || //If edited col is not in settings
editedSheet.getName() !== 'Sheet1' ||
row > 5
)
return;
var optionsDataRange = editedSheet
.getRange(1, 1, editedSheet.getLastRow(), 3)
.getValues();
/*Only get options where val is present in optionsDataRange*/
var options = optionsDataRange
.map(function(e) {
return e[SETTINGS[col] - 1] == val ? e[SETTINGS[col]] : null;
})
.filter(function(e, i, a) {
return e !== null && a.indexOf(e) === i;
});
var dv = SpreadsheetApp.newDataValidation()
.requireValueInList(options)
.build();
editedRange.offset(0, 1).setDataValidation(dv);
}
References:
Range
Array
I need to get the value for classname in below case. I am getting empty value. Let me know what I am missing. I need to find all distinct classes for every type.
var ga_type = new GlideAggregate('cmdb_rel_ci');
ga_type.groupBy('type');
ga_type.query();
if(ga_type.next()){
gs.log("Type : " + ga_type.type.getValue());
var ga_parent = new GlideAggregate('cmdb_rel_ci');
ga_parent.addQuery('type.sys_id', ga_type.type.getValue());
ga_parent.groupBy('parent.sys_class_name');
ga_parent.query();
var parent = [];
while(ga_parent.next()){
var p = {};
p.parentClassName = ga_parent.parent.sys_class_name.toString();
p.parentName = ga_parent.parent.name.toString();
gs.log("ParentClassName : " + p.parentClassName + " Parent Name : " + p.parentName);
parent.push(p);
}
}
As Tim says it's hard to know exactly what's being asked here, but it looks like you might be trying to get a list of all the types of relationships in cmdb_rel_ci. If that's the case, this should do it:
var count = new GlideAggregate('cmdb_rel_ci');
count.addAggregate('COUNT', 'type');
count.query();
var listOfParents = [];
while(count.next()){
var parent = count.type;
var parentCount = count.getAggregate('COUNT','type');
listOfParents.push(parent); //or parent.getDisplayValue()
gs.log(parent.getDisplayValue() + ": " + parentCount);
}
This is basically just the third example from the docs: GlideAggregate
IList<Item> items = new List<Item>();
items.Add(new Item
{
tag = "{" + Ann + "}",
value = "Anny"
});
items.Add(new Item
{
tag = "{" + John + "}",
value = "Johnny"
});
How can I use Linq to select tag with {John} and replace value with "Jane"?
LINQ is, as the name suggests, more of a query tools. So you can get specific item(s) that you want to modify from a collection using LINQ, but the modification itself is out-of-scope for LINQ.
Assuming that there is always maximum one match to your criteria, you can do as follows :
var john = items.FirstOrDefault(o => o.tag == "{John}");
if(john != null)
{
john.value = "Jane";
}
Otherwise, you can use LINQ Where(o => o.tag == "{John}") to get the target items for modification. But then you'll need to iterate through the result to actually update the value of each matched item.
items.Where(o => o.tag == "{"+John+"}").ToList().ForEach(item =>{
item.value = "Jane";
});
Here is working fiddle
I'm using LINQ's Union method to combine two or more collections. After that I'm trying to apply sorting to the combined collection by calling OrderBy on a field that is common to the collections. Here is how I am applying sorting:
combinedCollection.OrderBy(row => row["common_field"]);
combinedCollection is defined as:
Enumerable<DataRow> combinedCollection;
I need the sorting to be applied to the entire combined collection. For some reason, that is not happening. Instead I see there is sorting applied on some other field separately within each 'collection' block within the combined collection
And idea why??
First Edit
foreach (....)
{
if (combinedCollection != null)
{
combinedCollection = combinedCollection.Union(aCollection);
}
else
{
combinedCollection = aCollection;
}
}
Second Edit
_Cmd.CommandText = "SELECT Person.Contact.FirstName, Person.Contact.LastName, Person.Address.City, DATEDIFF(YY, HumanResources.Employee.BirthDate, GETDATE()) AS Age"
+ " FROM HumanResources.EmployeeAddress INNER JOIN"
+ " HumanResources.Employee ON HumanResources.EmployeeAddress.EmployeeID = HumanResources.Employee.EmployeeID INNER JOIN"
+ " Person.Address ON HumanResources.EmployeeAddress.AddressID = Person.Address.AddressID INNER JOIN"
+ " Person.Contact ON HumanResources.Employee.ContactID = Person.Contact.ContactID AND HumanResources.Employee.ContactID = Person.Contact.ContactID AND "
+ " HumanResources.Employee.ContactID = Person.Contact.ContactID AND HumanResources.Employee.ContactID = Person.Contact.ContactID";
DataTable employeeTable = new DataTable();
_Adpt.Fill(employeeTable);
DataRow[] allRows = null;
allRows = employeeTable.Select("");
IEnumerable<DataRow> filteredEmployeeRows;
filteredEmployeeRows = from row in allRows select row;
// Declare a variable to hold the city-filtered rows and set it to null for now
IEnumerable<DataRow> cityFilteredEmployeeRows = null;
//Copy filtered rows into a data table
DataTable filteredEmployeeTable = filteredEmployeeRows.CopyToDataTable<DataRow>();
foreach (DataRowView city in CityListBox.SelectedItems)
{
// create an exact copy of the data table
DataTable filteredEmployeeCopyTable = filteredEmployeeTable.Copy();
// Enumerate it
IEnumerable<DataRow> filteredEmployeeRowsInSingleCity = filteredEmployeeCopyTable.AsEnumerable();
// Apply the city filter
filteredEmployeeRowsInSingleCity = _ApplyCityFilter(filteredEmployeeRowsInSingleCity, city["City"].ToString());
if (cityFilteredEmployeeRows != null)
{
// Combine the filtered rows for this city with the overall collection of rows
cityFilteredEmployeeRows = cityFilteredEmployeeRows.Union(filteredEmployeeRowsInSingleCity);
}
else
{
cityFilteredEmployeeRows = filteredEmployeeRowsInSingleCity;
}
}
//apply ordering
cityFilteredEmployeeRows.OrderBy(row => row["Age"]);
//cityFilteredEmployeeRows.OrderByDescending(row => row["Age"]);
EmployeeGridView.DataSource = cityFilteredEmployeeRows.CopyToDataTable<DataRow>();
.......
private IEnumerable<DataRow> _ApplyCityFilter(IEnumerable<DataRow> filteredEmployeeRows, string city)
{
IEnumerable<DataRow> temp = filteredEmployeeRows;
filteredEmployeeRows = from row in temp
where row["City"].ToString() == city
select row;
return filteredEmployeeRows;
}
I think you have a problem with the LINQ lazy evaluation, I would have to investigate to find out wich part causes the problem.
Using the foreach(var item...) in lazy functions has already bitten me (because when executed later they all reference the last iterated item), but in your case it doesn't look like this is the problem.
To check it is the really the issue you can just use a DataRow[] in place of the IEnumerable<DataRow> and call .ToArray() after every LINQ function.
Edit: I'm not sure I got your code right but can't you just use:
var cities = CityListBox.SelectedItems.Cast<DataRowView>()
.Select(city => city["City"].ToString())
.ToArray();
var rows = allRows
.Where(r => cities.Contains((string)r["City"]))
.OrderBy(r => (int?)r["Age"])
.ToArray(); // if you want to evaluate directly, not mandatory
I have an object with two different integer properties in it, and I'm trying to get a a new object in Linq to Entities, combining two integer properties from the same object as concatenated strings, as follows
List<DateRange> collection = (from d in context.dates
select new DateRange
{
DateString = from s in context.Seasons
where s.SeasonID = d.DateID
select string.Format("{0} - {1}", s.StartYear, s.EndYear) }
).ToList<DateRange>();
The string concatenation of the years will not compile.
This will work in LINQ to Objects, provided that each object in objects is a class or struct containing "Number1" and "Number2" fields or properties:
var results = from o in objects
select string.Format("{0} - {1}", o.Number1, o.Number2);
(However, your original should work, as well....)
Assuming you are connecting to a database via LINQ to SQL/Entities, then the String.Format call will likely fail, as with those providers, the select clause is executed within the database. Not everything can be translated from C# into SQL.
To convert your database results into a string like you want to, the following should work:
var temp = (
from d in context.dates
from s in context.Seasons
where s.SeasonID == d.DateID
select new { s.StartYear, s.EndYear }
).ToList(); // Execute query against database now, before converting date parts to a string
var temp2 =
from t in temp
select new DateRange
{
DateString = t.StartYear + " - " + t.EndYear
};
List<DateRange> collection = temp2.ToList();
EDIT:
I had an additional thought. The String.Format call is most likely the problem. I am not sure if it would work or not, but what about a plain-jane concat:
List<DateRange> collection =
(from d in context.dates
select new DateRange
{
DateString = from s in context.Seasons
where s.SeasonID = d.DateID
select s.StartYear + " - " + s.EndYear
}
).ToList<DateRange>();
Your original code works if you really want what you wrote. However, if your really want to get from
var objects = new MyObject[]{
new MyObject {Int1 = 1, Int2 = 2},
new MyObject {Int1 = 3, Int2 = 4}};
something like 1 - 2 - 3 - 4 you can write
var strings = objects.Select(o = > string.Format("{0} - {1}", o.Int1, o.Int2).ToArray();
var output = string.Join(" - ", strings);
using System.Data.Objects.SqlClient;
:
:
List<DateRange> collection = (from d in context.dates
select new DateRange
{
DateString = from s in context.Seasons
where s.SeasonID = d.DateID
select SqlFunctions.StringConvert((double)s.StartYear) + " - " +
SqlFunctions.StringConvert((double)s.EndYear)
}).ToList<DateRange>();
The StringConvert method gets converted into the proper conversion function when the LINQ statement is converted to SQL for execution on the server.