if (DataList.Any(item => item.ID == int.Parse(Txtbox2.Text)))
{
Txtbox1.Text += string.Join(";", DataList.Select(o => o.DataString()));
}
I am trying to get the list into a textblock but only the items that meet a certain criteria.
The only thing I have is it displaying the whole list when the IF is met, is the any way for me to put a condition in the part that actually makes the list?
EDIT: all the DataString method is, is a method in the Data Class that converts all the vairous data types into a string output.
You want to use Where, rather than Any:
int value = int.Parse(Txtbox2.Text); //consider using TryParse here
var strings = DataList.Where(item => item.ID == value)
.Select(item => item.DataString());
Txtbox1.Text += string.Join(";", strings);
Also note that rather than parsing the textbox value over and over again, it's worth parsing it once and storing the result in a variable.
Related
I'm using DataTables.Mvc library for use with jQuery DataTables.
One of the methods is GetSortedColumns() which returns an array containing configurations for each column to be sorted.
Of interest in this object are the Name and SortDirection properties. Name is also the database table field name. SortDirection is either asc or desc.
At first ThenBy and ThenByDescending were undefined symbols, so I created ordered as IOrderedQueryable. This resolves the symbols, but I don't see any effect of these. Neither OrderBy, OrderByDescending, ThenBy nor ThenByDescending have any effect on the order of records in filteredRecords.
In Controller:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetUserSelections([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel)
{
// Column Sort
var filteredRecords = db.AspNetSelectorInputs.Select(si => si);
var sortedColumns = requestModel.Columns.GetSortedColumns();
var count = 0;
foreach (var column in sortedColumns)
{
var ordered = filteredRecords as IOrderedQueryable<AspNetSelectorInput>;
filteredRecords =
column.SortDirection == DataTables.Mvc.Column.OrderDirection.Ascendant
? count == 0
? ordered.OrderBy(c => column.Name)
: ordered.ThenBy(c => column.Name)
: count == 0
? ordered.OrderByDescending(c => column.Name)
: ordered.ThenByDescending(c => column.Name);
count++;
}
filteredRecords = filteredRecords.Select(si => si).Skip(requestModel.Start).Take(requestModel.Length);
....
Can anyone see why this doesn't affect ordering of filteredRecords?
Is there a better way?
It is sorting, on exactly what you've asked it to. But the lambda expressions aren't doing what you think. For example, you're doing .OrderBy(c => column.Name), which is sorting using a literal value of the name of the column which has the same value for every item in the collection (notice how the thing it is sorting on is not affected by c), so it appears not to sort your collection. For example, you might as well be doing .OrderBy(c => "Hello").
You would need to do something like .OrderBy(c => c.YourChoiceOfPropertyName). Except you can't do that because (presumably) the name of the property is a string value in column.Name. So you'll need to use reflection within the lambda to get the value of that property using c as the instance. This will need fixing on all the lambdas. For example, inside the loop:
var propertyInfo=typeof(AspNetSelectorInput)
.GetProperty(column.Name);
And replacement lambda expressions:
c=>propertyInfo.GetValue(c)
P.S. the two instances of .Select(si => si) seem to be redundant, unless I am missing something.
I have a list of objects, each with time data, id numbers, and a string descriptor in the type field. I wish to pull all the values to the front of the list with a certain string type, while keeping the order of those list elements the same, and the order of the rest of the list elements the same, just attached to the back of those with my desired string.
I've tried, after looking for similar SE questions,
list.OrderBy(x => x.type.Equals("Auto"));
which has no effect, though all other examples I could find sorted by number rather than by a string.
List Objects class definition:
public class WorkLoad
{
public long id;
public DateTime timestamp;
...
public String type;
}
...create various workload objects...
schedule.Add(taskX)
schedule.OrderBy(x => x.type.Equals("Manual"));
//has no effect currently
If you already have a sorted list I think the fastest way to resort it by "having a type of auto or not" without losing the original order (and without having to resort all over again) could be this:
var result = list.Where(x => x.type.Equals("Auto"))
.Concat(list.Where(x => !x.type.Equals("Auto")))
.ToList();
Update:
You commented that "everyting else should be sorted by time", so you can simply do this:
var result = list.OrderByDescending(x => x.type.Equals("Auto"))
.ThenBy(x => x.Time).ToList();
You can use multiple orderings in a sequence:
list.OrderBy(x => x.type == "Auto" ? 0 : 1).ThenBy(x => x.type);
I have a small application that iterates over the results of a "Saved Search" retrieving the values from several Custom Columns(simplified example):
var results = searchResults.Select(a => new
{
X = ((SearchColumnBooleanCustomField)a.basic.customFieldList
.First(b => b.scriptId == "custentityX")).searchValue
Y = ((SearchColumnDateCustomField)a.basic.customFieldList
.First(b => b.scriptId == "custentityY")).searchValue
Z = ((SearchColumnSelectCustomField)a.basic.customFieldList
.First(b => b.scriptId == "custentityZ")).searchValue.name
}
For most returned column types I get a value consistent with the type(bool/date/etc...) but with the "SearchColumnSelectCustomField" I don't get any value in the returned "searchValue.name", it's always null, however the "searchValue.internalID" column is always populated. So for some reason its getting the selection but not returning the value from that selection.
How do I access the text value that I can see from the NetSuite interface from SuiteTalk("searchValue.name")? Do I have to execute another query to retrieve all value key pairs related to that internalID? For every custom field? And if so then what is the purpose of the name field in the first place?
I've tried searching around for this, but there's not really allot of documentation on the subject(or on SuiteTalk in general), in other languages(PHP/Java) people mention "getSelectValue"(here, and briefly here), I could try this in C#, but I'm not sure if these apply or if that can be done for custom value selections.
Then there's some references for determining the values BEFORE the search, this seems like overkill to me, is it really that hard? I have dozens of CustomFields I would like to access in my final application. Seems like there should be an easier way...
As far as I know, the web service response will only contain the internalId and typeId for a SearchColumnSelectCustomField. In order to get the name, you'll have to first query NetSuite to find all custom lists and their values.
You can do this using a CustomListSearch and set the bodyFieldsOnly search preference to false. Pass in no criteria to the CustomListSearch and you'll be returned every custom list and their values. Just store there results in memory and reference it when reading the column values from your saved search.
I tried the answer posted by #Adud123 and it works great, Here's what the code looks like:
public Dictionary<string, Dictionary<long, string>> getCustomFieldLists()
{
return
nsService.search(new CustomListSearch())
.recordList.Select(a => (CustomList) a)
.ToDictionary(a => a.internalId,
a => a.customValueList.customValue
.ToDictionary(b => b.valueId, c => c.value));
}
var valueLookup = getCustomFieldLists();
var results = searchResults.Select(a => new
{
Z = (a.basic.customFieldList.Where(b => b.scriptId == "custentityZ")
.Select(a => (SearchColumnSelectCustomField)a)
.Select(a => valueLookup[a.searchValue.typeId][a.searchValue.internalId])
.First()
}
I have list and I need to search for items something like:
if the user searches for smi it will bring all items that include smi?
Any idea?
Check the following example
string serachKeyword ="o";
List<string> states = new List<string>();
states.Add("Frederick");
states.Add("Germantown");
states.Add("Arlington");
states.Add("Burbank");
states.Add("Newton");
states.Add("Watertown");
states.Add("Pasadena");
states.Add("Maryland");
states.Add("Virginia");
states.Add("California");
states.Add("Nevada");
states.Add("Ohio");
List<string> searchResults = states.FindAll(s => s.Contains(serachKeyword));
This will find all results that start with 'smi' (mySearchString)
foreach(var result in myList.Where(s => s.IndexOf(mySearchString) == 0))
{
// Do whatever
}
This will find any that contains 'smi' (mySearchString)
foreach(var result in myList.Where(s => s.IndexOf(mySearchString,StringComparison.InvariantCultureIgnoreCase) != -1))
{
// Do whatever
}
This will search for your text (ignoring case), and return any strings that contain the text.
that should work - Don't have IDE close by, but hope it helps
To search items that Include 'smi'
var result = list.Where(s => s.Contains("smi"));
If you want to grab all of the items that contain "smi" anywhere, like "smith" and "vesmit":
var list = myList.Where(m => m.Contains("smi"));
If you want to grab all of the items that contain "smi" at the start of the string, like "smith", "smitten", and "smile":
var list = myList.Where(m => m.BeginsWith("smi"));
If you want more flexibility, you can use a Regex
var list = myList.Where(m => Regex.IsMatch(m, "regexPattern"));
If you use a version of C# without LINQ you can use the Find method of the List as described here (it's got quite big sample on that page too).
The error message I receive is:
At least one object must implement IComparable
The code causing this is below:
private static IEnumerable<Result> setOrderBy(IEnumerable<Result> value, string order)
{
if (order.Equals("ASC"))
{
//value = value.OrderBy(c => c, new SearchService.ResultComparer<Attribute>());
value = value.OrderBy<Result>(o => o.StringAttributes.Where(p => p.AttributeName == "Title"), new SearchService.ResultComparer<Attribute>());
//value = value.OrderBy(o => o.StringAttributes.Where(p => p.AttributeName == "Title"), new SearchService.ResultComparer<AttributeItem>()));
}
if (order.Equals("DESC"))
{
value = value.OrderByDescending(c => c, new SearchService.ResultComparer<Attribute>());
//value = value.OrderByDescending(o => o.StringAttributes.Where(p => p.AttributeName == "MatterName"));
}
return value;
}
A little background:
In my MVC2 application, I perform a search in my Search controller. When I send my results to the Results view, I am trying to order the results alphabetically, in ascending or descending order.
However, when I write out the logic to set the OrderBy property for my result object I get the squiggly red line underneath the code (as seen in VS2008). For some reason the method doesn't like the data model I am trying to do a sort upon. Each Result object has various properties, one of which is a list of attributes of type string (hence the name StringAttributes) I am trying to sort each Result object in my IEnumerable collection by the value of one of the String Attributes which is present in ALL of my result records.
Help please!
I think you need to use First() or Single instead of Where() in the place where you are picking out the Attribute to order by. At the moment you are asking OrderBy to calculate order using an IEnumerable<Attribute>, rather than a particular attribute.
value = value.OrderBy<Result>(o => o.StringAttributes.Single(p => p.AttributeName == "Title"), new SearchService.ResultComparer<Attribute>());
or
value = value.OrderBy<Result>(o => o.StringAttributes.First(p => p.AttributeName == "Title"), new SearchService.ResultComparer<Attribute>());