Implement sort in Nvelocity - c#

I have a class which has approx 50 properties, instances of this class is added to a list. This list is then added to a Velocity context. Now, I would like to sort this data. Which field, or if it is ascending or descending is not known until the template is being parsed.
Resources I've looked into:
Better way to use Velocity's GenericTools in a Standalone app?
Velocity foreach sort list
http://velocity.apache.org/tools/devel/generic/
Based on the resources listed here I can't figure out how to solve this. Is the GenericTools available for the Castle's Nvelocity? If not, how may I implement such a generic sort I'm asking for here?

My solution was to write my own sort-class and add this as a context to nvelocity. I'm passing the field to sort on as string and accessing it as reflection. I'm also setting sort ascending or descending by string value. I'm also passing in the name of the comparer and accessing this with reflection as well. I'm then using the List method OrderBy or OrderByDescending with the choosen field and comparer.
I did find parts of the code here: http://zootfroot.blogspot.co.uk/2009/10/dynamic-linq-orderby.html
public class NvelocitySort
{
public List<MyObject> Sort(List<MyObject> list, string fieldAndMode, string comparerName)
{
fieldAndMode = fieldAndMode.Trim();
// Split the incoming string to get the field name and sort ascending or descending
string[] split = fieldAndMode.Split(' ');
// Set default sort mode
string mode = "asc";
// If sort mode not specified, this will be the field name
string field = fieldAndMode;
// If sort mode added split length shall be 2
if (split.Length == 2)
{
field = split[0];
if (split[1].ToLower() == "asc" || split[1].ToLower() == "ascending") mode = "asc";
if (split[1].ToLower() == "desc" || split[1].ToLower() == "descending") mode = "desc";
}
// If length is more than 2 or 0, return same list as passed in
else if (split.Length > 2 || split.Length == 0)
{
return list;
}
// Get comparer based on comparer name
IComparer<string> comparer = (IComparer<string>)Activator.CreateInstance(Type.GetType(string.Format("Namespace.{0}", comparerName)));
// Choose the sort order
if (mode == "asc")
return list.OrderBy(item => item.GetReflectedPropertyValue(field), comparer).ToList();
if (mode == "desc")
return list.OrderByDescending(item => item.GetReflectedPropertyValue(field), comparer).ToList();
// If sort order not asc/desc return same list as passed in
return list;
}
}
This is the reflection method for retrieving the field.
public static string GetReflectedPropertyValue(this object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}
Simple comparer example:
public class TextComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y);
}
}
Added to Nvelocity context like this:
this.velocityContext.Put("sorter", new NvelocitySort());
Accessed from Nvelocity template like this:
#foreach($item in $sorter.Sort($listObject, "Name desc", "TextComparer"))
$item.Name
#end
Hope it helps someone else...
EDIT:
Found an even better way to do it (implements multiple fields sorting):
http://www.codeproject.com/Articles/280952/Multiple-Column-Sorting-by-Field-Names-Using-Linq

Related

Compare values of objects in two lists

I have two ObservableCollection<Model>, each model has 10 properties and there are approximately 30 objects within both collections in the beggining. They basicaly work like this: initialy there are saved the same objects in both OCs, where one is the original and the other one is where changes are happening. Basicaly I would need the first one just to see if changes have been made to compare the values. So far I have come up with
list1.SequenceEquals(list2);
but this only works if i add a new object, it does not recognize changes in the actual properties. Is there a fast way this could be done or I need to do foreach for every object and compare individual properties one by one? Because there may be more than 30 objects to compare values. Thanks.
Is there a fast way this could be done or I need to do foreach for every object and compare individual properties one by one?
If by "fast" you mean "performant" then comparing property-by property is probably the fastest way. If by "fast" you mean "less code to write" then you could use reflection to loop through the properties and compare the values of each item.
Note that you'll probably spend more time researching, writing, and debugging the reflection algorithm that you would just hand-coding the property comparisons.
A simple way to use the built-in Linq methods would be do define an IEqualityComparer<Model> that defines equality of two Model objects:
class ModelEqualityComparer : IEqualityComparer<Model>
{
public bool Equals(Model m1, Model m2)
{
if(m1 == null || 2. == null)
return false;
if (m1.Prop1 == m2.Prop1
&& m1.Prop2 == m2.Prop2
&& m1.Prop3 == m2.Prop3
...
)
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(Model m)
{
int hCode = m.Prop1.GetHashCode();
hCode = hCode * 23 + ^ m.Prop2.GetHashCode();
hCode = hCode * 23 + ^ m.Prop32.GetHashCode();
...
return hCode;
}
}
I think you can compare them defining a custom IEqualityComparer<T>, and using the overload of IEnumerable.SequenceEqualsthat supports a custom comparer: Enumerable.SequenceEqual<TSource> Method (IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)more info about it here: http://msdn.microsoft.com/it-it/library/bb342073(v=vs.110).aspx
I'll post here an usage example from that page in case it goes missing:
Here is how to define a IEqualityComparer<T>
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
// Custom comparer for the Product class
class ProductComparer : IEqualityComparer<Product>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(Product x, Product y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Code == y.Code && x.Name == y.Name;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = product.Code.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
Here's how to use it:
Product[] storeA = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 } };
Product[] storeB = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 } };
bool equalAB = storeA.SequenceEqual(storeB, new ProductComparer());
Console.WriteLine("Equal? " + equalAB);
/*
This code produces the following output:
Equal? True
*/

How to sort strings by a different value

I've tried looking for an existing question but wasn't sure how to phrase this and this retrieved no results anywhere :(
Anyway, I have a class of "Order Items" that has different properties. These order items are for clothing, so they will have a size (string).
Because I am OCD about these sorts of things, I would like to have the elements sorted not by the sizes as alphanumeric values, but by the sizes in a custom order.
I would also like to not have this custom order hard-coded if possible.
To break it down, if I have a list of these order items with a size in each one, like so:
2XL
S
5XL
M
With alphanumeric sorting it would be in this order:
2XL
5XL
M
S
But I would like to sort this list into this order (from smallest size to largest):
S
M
2XL
5XL
The only way I can think of to do this is to have a hard-coded array of the sizes and to sort by their index, then when I need to grab the size value I can grab the size order array[i] value. But, as I said, I would prefer this order not to be hard-coded.
The reason I would like the order to be dynamic is the order items are loaded from files on the hard disk at runtime, and also added/edited/deleted by the user at run-time, and they may contain a size that I haven't hard-coded, for example I could hard code all the way from 10XS to 10XL but if someone adds the size "110cm" (aka a Medium), it will turn up somewhere in the order that I don't want it to, assuming the program doesn't crash and burn.
I can't quite wrap my head around how to do this.
Also, you could create a Dictionary<int, string> and add Key as Ordering order below. Leaving some gaps between Keys to accomodate new sizes for the future. Ex: if you want to add L (Large), you could add a new item as {15, "L"} without breaking the current order.
Dictionary<int, string> mySizes = new Dictionary<int, string> {
{ 20, "2XL" }, { 1, "S" },
{ 30, "5XL" }, { 10, "M" }
};
var sizes = mySizes.OrderBy(s => s.Key)
.Select(s => new {Size = s.Value})
.ToList();
You can use OrderByDescending + ThenByDescending directly:
sizes.OrderByDescending(s => s == "S")
.ThenByDescending( s => s == "M")
.ThenByDescending( s => s == "2XL")
.ThenByDescending( s => s == "5XL")
.ThenBy(s => s);
I use ...Descending since a true is similar to 1 whereas a false is 0.
I would implement IComparer<string> into your own TShirtSizeComparer. You might have to do some regular expressions to get at the values you need.
IComparer<T> is a great interface for any sorting mechanism. A lot of built-in stuff in the .NET framework uses it. It makes the sorting reusable.
I would really suggest parsing the size string into a separate object that has the size number and the size size then sorting with that.
You need to implement the IComparer interface on your class. You can google how to do that as there are many examples out there
you'll have to make a simple parser for this. You can search inside the string for elements like XS XL and cm" if you then filter that out you have your unit. Then you can obtain the integer that is the value. If you have that you can indeed use an IComparer object but it doesn't have that much of an advantage.
I would make a class out of Size, it is likely that you will need to add more functionality to this in the future. I added the full name of the size, but you could also add variables like width and length, and converters for inches or cm.
private void LoadSizes()
{
List<Size> sizes = new List<Size>();
sizes.Add(new Size("2X-Large", "2XL", 3));
sizes.Add(new Size("Small", "S", 1));
sizes.Add(new Size("5X-Large", "5XL", 4));
sizes.Add(new Size("Medium", "M", 2));
List<string> sizesShortNameOrder = sizes.OrderBy(s => s.Order).Select(s => s.ShortName).ToList();
//If you want to use the size class:
//List<Size> sizesOrder = sizes.OrderBy(s => s.Order).ToList();
}
public class Size
{
private string _name;
private string _shortName;
private int _order;
public string Name
{
get { return _name; }
}
public string ShortName
{
get { return _shortName; }
}
public int Order
{
get { return _order; }
}
public Size(string name, string shortName, int order)
{
_name = name;
_shortName = shortName;
_order = order;
}
}
I implemented TShirtSizeComparer with base class Comparer<object>. Of course you have to adjust it to the sizes and objects you have available:
public class TShirtSizeComparer : Comparer<object>
{
// Compares TShirtSizes and orders them by size
public override int Compare(object x, object y)
{
var _sizesInOrder = new List<string> { "None", "XS", "S", "M", "L", "XL", "XXL", "XXXL", "110 cl", "120 cl", "130 cl", "140 cl", "150 cl" };
var indexX = -9999;
var indexY = -9999;
if (x is TShirt)
{
indexX = _sizesInOrder.IndexOf(((TShirt)x).Size);
indexY = _sizesInOrder.IndexOf(((TShirt)y).Size);
}
else if (x is TShirtListViewModel)
{
indexX = _sizesInOrder.IndexOf(((TShirtListViewModel)x).Size);
indexY = _sizesInOrder.IndexOf(((TShirtListViewModel)y).Size);
}
else if (x is MySelectItem)
{
indexX = _sizesInOrder.IndexOf(((MySelectItem)x).Value);
indexY = _sizesInOrder.IndexOf(((MySelectItem)y).Value);
}
if (indexX > -1 && indexY > -1)
{
return indexX.CompareTo(indexY);
}
else if (indexX > -1)
{
return -1;
}
else if (indexY > -1)
{
return 1;
}
else
{
return 0;
}
}
}
To use it you just have a List or whatever your object is and do:
tshirtList.Sort(new TShirtSizeComparer());
The order you have "hard-coded" is prioritized and the rest is put to the back.
I'm sure it can be done a bit smarter and more generalized to avoid hard-coding it all. You could e.g. look for sizes ending with an "S" and then check how many X's (e.g. XXS) or the number before X (e.g. 2XS) and sort by that, and then repeat for "L" and perhaps other "main sizes".

Is there an Algorithm to index a collection on permutation of properties?

Given:
IMatchCriteria {
string PropA{get;}
string PropB{get;}
int? PropC {get;}
int? PropD {get;}
}
IReportRecord : IMatchCriteria {...}
IMatchCriteriaSet : IMatchCriteria {
int MatchId {get;}
double Limit{get;}
}
public class Worker{
private List<IMatchCriteriaSet> _matchers = GetIt();
//Expecting this list to be huge, ***upto 0.1m***. Some of the sample matchers:
// MatchId=1, Limit=1000, PropA=A, PropC=101, PropD=201
// MatchId=2, Limit=10, PropA=A
// MatchId=3, Limit=20, PropC=101
// MatchId=4, Limit=500, PropD=201
//Based on sample entries:
//Input: reportRecord{ PropA=A, PropC=101 }, Ouput: 1000, 20
//Input: reportRecord{ PropA=A1, PropC=102, PropD=201 }, Ouput: 500
public IEnumerable<double> GetMatchingLimits(IReportRecord reportRecord) {
//Bad, very bad option:
foreach(var matcher in _matchers){
var matchFound=true;
if(reportRecord.PropA!=null && reportRecord.PropA!=matcher.PropA){
continue;
}
if(reportRecord.PropB!=null && reportRecord.PropA!=matcher.PropB){
continue;
}
if(reportRecord.PropC!=null && reportRecord.PropC.Value!=matcher.PropC.Value){
continue;
}
if(reportRecord.PropD!=null && reportRecord.PropD.Value!=matcher.PropD.Value){
continue;
}
yield return matcher.Limit;
}
}
}
Note: Expecting IMatchCriteriaSet to be 0.1m records.
Expecting GetMatchingLimits to be called 1m times.
The requirement is to do all this for a real-time application.
Essentially what I need is a way to index list of IMatchCriteria. But can not use Dictionary because my key is not defined.
Looking for some algorithm to tackle this problem efficiently.
Any suggested solution in scope of .net (not just c#) would be useful.
Thanks.
Use one dictionary for each indexable property, mapping to a set of matchers. Then you can do a dictionary lookup for every property that is set in your record (logarithmic complexity), and intersect the resulting sets. Start with the smallest result set and whittle it down to get the best run time.

Using C# Dictionary to parse log file

I am trying to parse a rather long log file and creating a better more manageable listing of issues.
I am able to read and parse out the individual log line by line, but what I need to do is display only unique entries, as some errors occur more often than others and are always recorded with identical text.
What I was going to try to do was create a Dictionary object to hold each unique entry and as I work through the log file, search the Dictionary object to see if the same values are already in there.
Here is a crude sample of the code I have (a work in progress, I hope I have all syntax right) that does not work. For some reason this script never sees any distinct entries (if statement never passes):
string[] rowdta = new string[4];
Dictionary<string[], int> dict = new Dictionary<string[], int>();
int ctr = -1;
if (linectr == 1)
{
ctr++;
dict.Add(rowdta, ctr);
}
else
{
foreach (KeyValuePair<string[], int> pair in dict)
{
if ((pair.Key[1] != rowdta[1]) || (pair.Key[2] != rowdta[2])| (pair.Key[3] != rowdta[3]))
{
ctr++;
dict.Add(rowdta, ctr);
}
}
}
Some sample data:
First line
rowdta[0]="ErrorType";
rowdta[1]="Undefined offset: 0";
rowdta[2]="/url/routesDisplay2.svc.php";
rowdta[3]="Line Number 5";
2nd line
rowdta[0]="ErrorType";
rowdta[1]="Undefined offset: 0";
rowdta[2]="/url/routesDisplay2.svc.php";
rowdta[3]="Line Number 5";
3rd line
rowdta[0]="ErrorType";
rowdta[1]="Undefined variable: fvmsg";
rowdta[2]="/url/processes.svc.php";
rowdta[3]="Line Number 787";
So, with this, the Dictionary will have 2 items in it, first line and 3rd line.
I have also tried this with the following which nalso does not find any variations in the log file text.
if (!dict.ContainsKey(rowdta)) {}
Can someone please help me get this syntax right? I am just a newbie at C# but this should be relatively straightforward. As always, I am thinking that this should be enough information to get the conversation started. If you want/need more detail, please let me know.
Either create a wrapper for your strings which implements IEquatable.
public class LogFileEntry :IEquatable<LogFileEntry>
{
private readonly string[] _rows;
public LogFileEntry(string[] rows)
{
_rows = rows;
}
public override int GetHashCode()
{
return
_rows[0].GetHashCode() << 3 |
_rows[2].GetHashCode() << 2 |
_rows[1].GetHashCode() << 1 |
_rows[0].GetHashCode();
}
#region Implementation of IEquatable<LogFileEntry>
public override bool Equals(Object obj)
{
if (obj == null)
return base.Equals(obj);
return Equals(obj as LogFileEntry);
}
public bool Equals(LogFileEntry other)
{
if(other == null)
return false;
return _rows.SequenceEqual(other._rows);
}
#endregion
}
Then use that in your dictionary:
var d = new Dictionary<LogFileEntry, int>();
var entry = new LogFileEntry(rows);
if( d.ContainsKey(entry) )
{
d[entry] ++;
}
else
{
d[entry] = 1;
}
Or create a custom comparer similar to that proposed by #dasblinkenlight and use as follows
public class LogFileEntry
{
}
public class LogFileEntryComparer : IEqualityComparer<LogFileEntry>{ ... }
var d = new Dictionary<LogFileEntry, int>(new LogFileEntryComparer());
var entry = new LogFileEntry(rows);
if( d.ContainsKey(entry) )
{
d[entry] ++;
}
else
{
d[entry] = 1;
}
The reason that you see the problem is that an array of strings cannot be used as a key in a dictionary without supplying a custom IEqualityComparer<string[]> or writing a wrapper around it.
EDIT Here is a quick and dirty implementation of a custom comparer:
private class ArrayEq<T> : IEqualityComparer<T[]> {
public bool Equals(T[] x, T[] y) {
return x.SequenceEqual(y);
}
public int GetHashCode(T[] obj) {
return obj.Sum(o => o.GetHashCode());
}
}
Here is how you can use it:
var dd = new Dictionary<string[], int>(new ArrayEq<string>());
dd[new[] { "a", "b" }] = 0;
dd[new[] { "a", "b" }]++;
dd[new[] { "a", "b" }]++;
Console.WriteLine(dd[new[] { "a", "b" }]);
The problem is that array equality is reference equality. In other words, it does not depend on the values stored in the array, it depends only on the identity of the array.
Some solutions
use Tuple to hold the row data
use an anonymous type to hold the row data
create a custom type to hold the row data, and, if it is a class, override Equals and GetHashCode.
create a custom implementation of IEqualityComparer to compare the arrays according to their values, and pass that to the dictionary when you create it.

Removing duplicates from a list with "priority"

Given a collection of records like this:
string ID1;
string ID2;
string Data1;
string Data2;
// :
string DataN
Initially Data1..N are null, and can pretty much be ignored for this question. ID1 & ID2 both uniquely identify the record. All records will have an ID2; some will also have an ID1. Given an ID2, there is a (time-consuming) method to get it's corresponding ID1. Given an ID1, there is a (time-consuming) method to get Data1..N for the record. Our ultimate goal is to fill in Data1..N for all records as quickly as possible.
Our immediate goal is to (as quickly as possible) eliminate all duplicates in the list, keeping the one with more information.
For example, if Rec1 == {ID1="ABC", ID2="XYZ"}, and Rec2 = {ID1=null, ID2="XYZ"}, then these are duplicates, --- BUT we must specifically remove Rec2 and keep Rec1.
That last requirement eliminates the standard ways of removing Dups (e.g. HashSet), as they consider both sides of the "duplicate" to be interchangeable.
How about you split your original list into 3 - ones with all data, ones with ID1, and ones with just ID2.
Then do:
var unique = allData.Concat(id1Data.Except(allData))
.Concat(id2Data.Except(id1Data).Except(allData));
having defined equality just on the basis of ID2.
I suspect there are more efficient ways of expressing that, but the fundamental idea is sound as far as I can tell. Splitting the initial list into three is simply a matter of using GroupBy (and then calling ToList on each group to avoid repeated queries).
EDIT: Potentially nicer idea: split the data up as before, then do:
var result = new HashSet<...>(allData);
result.UnionWith(id1Data);
result.UnionWith(id2Data);
I believe that UnionWith keeps the existing elements rather than overwriting them with new but equal ones. On the other hand, that's not explicitly specified. It would be nice for it to be well-defined...
(Again, either make your type implement equality based on ID2, or create the hash set using an equality comparer which does so.)
This may smell quite a bit, but I think a LINQ-distinct will still work for you if you ensure the two compared objects come out to be the same. The following comparer would do this:
private class Comp : IEqualityComparer<Item>
{
public bool Equals(Item x, Item y)
{
var equalityOfB = x.ID2 == y.ID2;
if (x.ID1 == y.ID1 && equalityOfB)
return true;
if (x.ID1 == null && equalityOfB)
{
x.ID1 = y.ID1;
return true;
}
if (y.ID1 == null && equalityOfB)
{
y.ID1 = x.ID1;
return true;
}
return false;
}
public int GetHashCode(Item obj)
{
return obj.ID2.GetHashCode();
}
}
Then you could use it on a list as such...
var l = new[] {
new Item { ID1 = "a", ID2 = "b" },
new Item { ID1 = null, ID2 = "b" } };
var l2 = l.Distinct(new Comp()).ToArray();
I had a similar issue a couple of months ago.
Try something like this...
public static List<T> RemoveDuplicateSections<T>(List<T> sections) where T:INamedObject
{
Dictionary<string, int> uniqueStore = new Dictionary<string, int>();
List<T> finalList = new List<T>();
int i = 0;
foreach (T currValue in sections)
{
if (!uniqueStore.ContainsKey(currValue.Name))
{
uniqueStore.Add(currValue.Name, 0);
finalList.Add(sections[i]);
}
i++;
}
return finalList;
}
records.GroupBy(r => r, new RecordByIDsEqualityComparer())
.Select(g => g.OrderByDescending(r => r, new RecordByFullnessComparer()).First())
or if you want to merge the records, then Aggregate instead of OrderByDescending/First.

Categories