Unity - Sorting a nested list - list

I'm trying to figure out how to sort a nested List in Unity. I have my:
[System.Serializable]
public class HistoryRecordList
{
public int recordDate;
public string record;
}
And my list here:
public class InputMachine : MonoBehaviour
{
public List<HistoryRecordList> historyRecords = new List<HistoryRecordList>();
public void AddToHistory(int ID, string description)
{
HistoryRecordList list = new HistoryRecordList();
list.recordDate = ID;
list.record = description;
historyRecords.Add(list);
}
}
I like to sort the list "historyRecords" by recordDate;
I know, there is a list.Sort() function but I don't know how to apply it to a nested list. Maybe someone knows how to do it?

There are many ways to solve this problem.
LINQ
Implement (Ascending)
private static List<HistoryRecordList> SortRecordDate(IEnumerable<HistoryRecordList> list)
{
return list.OrderBy(x => x.recordDate).ToList();
}
How to use
historyRecords = SortRecordDate(historyRecords);
List<>.Sort(Comparison<T>)
Implement (Ascending)
private static void SortRecordDate(List<HistoryRecordList> list)
{
list.Sort((x, y) => x.recordDate.CompareTo(y.recordDate));
}
Implement (Descending)
private static void SortRecordDate(List<HistoryRecordList> list)
{
list.Sort((x, y) => y.recordDate.CompareTo(x.recordDate));
}
How to use
SortRecordDate(historyRecords);
Hope your problem is solved :)

Related

How to combine PropertyData and AutoNSubstituteData attributes in xunit/autofixture?

I am using the [AutoNSubstituteData] attribute, which was posted here:
AutoFixture, xUnit.net, and Auto Mocking
I would like to combine this with the [PropertyData("")] attribute from xunit extensions.
This is my test:
public static IEnumerable<string[]> InvalidInvariant
{
get
{
yield return new string[] { null };
yield return new [] { string.Empty };
yield return new [] { " " };
}
}
[Theory, AutoNSubstituteData, PropertyData("InvalidInvariant")]
public void TestThatGuardsAreTriggeredWhenConnectionStringArgumentIsInvalid(
IDeal deal,
IDbConnection conn,
IDb db,
ISender sender,
string invalidConnString,
string query)
{
deal.Init.Group.Returns(Group.A);
deal.Aggr.Group.Returns(Group.A);
deal.Product.Commodity.Returns(Product.Commodity.E);
var sut = new Handler(db, sender);
Assert.Throws<ArgumentException>(() =>
sut.HandleDeal(deal, conn, invalidConnString, query));
}
Is there a way to combine these attributes or to get the desired functionality (mock everything, except for invalidConnstring, which should be filled with the property-data)?
There are two ways to do this:
Option 1 - Using AutoFixture.Xunit and the CompositeDataAttribute class:
internal class AutoNSubstituteDataAttribute : AutoDataAttribute
{
internal AutoNSubstituteDataAttribute()
: base(new Fixture().Customize(new AutoNSubstituteCustomization()))
{
}
}
internal class AutoNSubstitutePropertyDataAttribute : CompositeDataAttribute
{
internal AutoNSubstitutePropertyDataAttribute(string propertyName)
: base(
new DataAttribute[] {
new PropertyDataAttribute(propertyName),
new AutoNSubstituteDataAttribute() })
{
}
}
Define the test cases as below:
public class Scenario
{
public static IEnumerable<object[]> InvalidInvariantCase1
{
get
{
yield return new string[] { null };
}
}
public static IEnumerable<object[]> InvalidInvariantCase2
{
get
{
yield return new string[] { string.Empty };
}
}
public static IEnumerable<object[]> InvalidInvariantCase3
{
get
{
yield return new string[] { " " };
}
}
}
Then declare the parameterized test as:
public class Scenarios
{
[Theory]
[AutoNSubstitutePropertyData("InvalidInvariantCase1")]
[AutoNSubstitutePropertyData("InvalidInvariantCase2")]
[AutoNSubstitutePropertyData("InvalidInvariantCase3")]
public void AParameterizedTest(
string invalidConnString,
IDeal deal,
IDbConnection conn,
IDb db,
ISender sender,
string query)
{
}
}
Please note that the parameterized parameter invalidConnString have to be declared before the other parameters.
Option 2 - Using Exude:
public class Scenario
{
public void AParameterizedTest(
IDeal deal,
IDbConnection conn,
IDb db,
ISender sender,
string invalidConnString,
string query)
{
}
[FirstClassTests]
public static TestCase<Scenario>[] RunAParameterizedTest()
{
var testCases = new []
{
new
{
invalidConnString = (string)null
},
new
{
invalidConnString = string.Empty
},
new
{
invalidConnString = " "
}
};
var fixture = new Fixture()
.Customize(new AutoNSubstituteCustomization());
return testCases
.Select(tc =>
new TestCase<Scenario>(
s => s.AParameterizedTest(
fixture.Create<IDeal>(),
fixture.Create<IDbConnection>(),
fixture.Create<IDb>(),
fixture.Create<ISender>(),
tc.invalidConnString,
fixture.Create<string>())))
.ToArray();
}
}
The [Theory] attribute works by looking for one or more 'data source attributes'; for example
[InlineData]
[PropertyData]
[ClassData]
etc.
The [AutoData] attribute is just another such attribute, as is your derived [AutoNSubstituteData] attribute.
It's possible to add more than one 'data source attribute' to the same [Theory], as witnessed by the idiomatic use of the [InlineData] attribute:
[Theory]
[InlineData("foo")]
[InlineData("bar")]
[InlineData("baz")]
public void MyTest(string text)
This produces three test cases.
It's also possible to combine [PropertyData] and [AutoData], but it probably doesn't do what you want it to do. This:
[Theory]
[AutoNSubstituteData]
[PropertyData("InvalidInvariant")]
public void MyTest(/* parameters go here */)
will result in 1 + n test cases:
1 test case from [AutoNSubstituteData]
n test cases from the InvalidInvariant property
These two attributes know nothing about each other, so you can't combine them in the sense that they're aware of each other.
However, when you're implementing a property, you can write whatever code you'd like, including using a Fixture instance, so why not just do this?
public static IEnumerable<string[]> InvalidInvariant
{
get
{
var fixture = new Fixture().Customize(new MyConventions());
// use fixture to yield values...,
// using the occasional hard-coded test value
}
}
Another option is to use derive from the InlineAutoDataAttribute, which would enable you to write your test cases like this:
[Theory]
[MyInlineAutoData("foo")]
[MyInlineAutoData("bar")]
[MyInlineAutoData("baz")]
public void MyTest(string text, string someOtherText, int number, Guid id)
This would cause the first argument (text) to be populated with the constants from the attributes, while the remaining parameters are populated by AutoFixture.
Theoretically, you may also be able to combine the [AutoData] and [PropertyData] attributes using the CompositeDataAttribute, but it may not work the way you'd like.
Finally, you could consider using Exude for true first-class parameterized tests.
I have implemented an AutoPropertyDataAttribute that combines xUnit's PropertyDataAttribute with AutoFixture's AutoDataAttribute. I posted it as an answer here.
In your case you will need to inherit from the attribute in the same way as you would from an AutoDataAttribute, with the exception that you pass a fixture creation function instead of an instance:
public class AutoNSubPropertyDataAttribute : AutoPropertyDataAttribute
{
public AutoNSubPropertyDataAttribute(string propertyName)
: base(propertyName, () => new Fixture().Customize(new AutoNSubstituteCustomization()))
{
}
}

Strategy Pattern C++

I want implement the strategy pattern in C++ but I have a doubt. Alwyas the strategy patterns examples are than follow code (in C#). I want modify the client, i.e MainClass, such that choose the concrete strategy will be dynamic way.
For example, passing the strategy name by the args[] parameters of the main method. How I will be able to implement this without modify the properties of this pattern?.
namespace StrategyPatterns
{
// Interface definition for a Sort algorithm
public interface ISort
{
void Sort(List<string> list)
}
// QuickSort implementation
public class CQuickSorter : ISort
{
void Sort(List<string> list)
{
// Here will come the actual imp
}
}
// BubbleSort
public class CBubbleSort : ISort
{
void Sort(List<string> list)
{
// The actual imp of the sort
}
}
public class Context
{
private ISort sorter;
public Context(ISort sorter)
{
// We pass the context the strategy to use
this.sorter = sorter;
}
public ISort Sorter
{
get{return sorter;)
}
}
public class MainClass
{
static void Main()
{
List<string> myList = new List<string>();
myList.Add("Hello world");
myList.Add("Another item");
Contexto cn = new Contexto(new CQuickSorter());
cn.Sorter.Sort(myList);
cn = new Contexto(new CBubbleSort());
cn.Sorter.Sort(myList);
}
}
}
We do not have reflection in C++, that is the concept you need to get this to work right.. The alternative that I can think of, is to make a factory method as below..
ISort* CreateSorter(SortType type)
{
switch (type){
case QUICK_SORT: return new CQuickSorter();
...
}
}
I use an enum for cleaner code, but you can change that into a string, as long as you are able to understand my basic point.
I would give the context class a templated factory function setSorter and handle the entire lifetime of the sorter objects internally.
class Interface { //this class and all sorting clases could be templated to be able to deal with sorting lists of different data types
std::unique_ptr<ISort> sorter_;
public:
Interface():sorter_(new CQuickSorter()){ //CQuickSorter is the default sorter
}
template<typename T>
setSorter(){ //one could also use perfect forwarding to pass arguments to T's constructor
sorter_.reset(new T());
}
void sort(std::list<string> &list){
sorter_->sort(list);
}
};
int main(){
std::list<int> li;
Interface cn;
cn.sort(li); //using a default sort
cn.setSorter<CBubbleSort>();
cn.sort(li); //using bubble sort
}

How to get NUnit to test all values in a list, rather than just the first failure

Just some example code here, but I have lists of strings that I want to test my functions against. The part that I don't like is that NUnit stops in each test when the first Assert fails. I'd like to test each value and report each failure, rather than just the first one. I don't want to have to write a new [Test] function for each string though.
Is there a way to do this?
using NUnit.Framework;
using System.Collections.Generic;
namespace Examples
{
[TestFixture]
public class ExampleTests
{
private List<string> validStrings = new List<string> { "Valid1", "valid2", "valid3", "Valid4" };
private List<string> invalidStrings = new List<string> { "Invalid1", "invalid2", "invalid3", "" };
[Test]
public void TestValidStrings()
{
foreach (var item in validStrings)
{
Assert.IsTrue(item.Contains("valid"), item);
}
}
[Test]
public void TestInvalidStrings()
{
foreach (var item in invalidStrings)
{
Assert.IsFalse(item.Contains("invalid"), item);
}
}
}
}
Use the [TestCaseSource] attribute to specify values to pass into your (now parameterized) test method.
We use this a lot in Noda Time to test a lot of cases with different cultures and strings.
Here's your example, converted to use it:
using NUnit.Framework;
using System.Collections.Generic;
// Namespace removed for brevity
[TestFixture]
public class ExampleTests
{
private List<string> validStrings = new List<string>
{ "Valid1", "valid2", "valid3", "Valid4" };
private List<string> invalidStrings = new List<string>
{ "Invalid1", "invalid2", "invalid3", "" };
[Test]
[TestCaseSource("validStrings")]
public void TestValidStrings(string item)
{
Assert.IsTrue(item.Contains("valid"), item);
}
[Test]
[TestCaseSource("invalidStrings")]
public void TestInvalidStrings(string item)
{
Assert.IsFalse(item.Contains("invalid"), item);
}
}
Note that another option is to use [TestCase] which means you don't need separate variables for your test data.

Struts2 get object attribute from select tag

My problem is that I don't succeed in getting the attribute of the object of the list of my select tag.
I have a select tag in my .jsp like this :
<s:select list="listFonction" listKey="code" listValue="Libelle"
name="fonctionSelectionne" value="defaultFonction" />
and in my action, i declared an arraylist (with getter and setter) :
private ArrayList<Fonction> listFonction = new ArrayList<Fonction>();
I also have another class Fonction :
public class Fonction {
private int code;
private String libelle;
public Fonction(int code, String libelle)
{
this.code = code;
this.libelle =libelle;
}
public Fonction()
{
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
}
To get the selected value in my action i declared (whith getter and setter):
Private String fonctionSelectionne;
but i am just abbled to get the code (listkey) of my object with getFonctionSelectionne.
I want to get the code attribute (listkey) and the libelle attribute (listvalue).
Does anyone know how help me ?
thanks
2 points:
it should be libelle, not Libelle
<s:select list="listFonction" listKey="code" listValue="libelle"
name="fonctionSelectionne" value="defaultFonction" />
for list="listFunction", you need getter Collection getListFunction(){} in your action class
UPDATE
i'am not sure to this. but you can give a try.
here is the idea, don't deliver a list, but a map to select tag
Map getListFunction(){
Map<Object, String> map;
Function f = new Function(1, "test");
map.put(f, f.libelle);
return map;
}
then in the jsp:
<s:select list="listFonction" listKey="key" listValue="value"
name="fonctionSelectionne"/>
You should make the setter of the attribute listFonction on the ClassAction

Return a concrete implementation in a list

I know this doesnt compile but why shouldnt it?
public interface IReportService {
IList<IReport> GetAvailableReports();
IReport GetReport(int id);
}
public class ReportService : IReportService {
IList<IReport> GetAvailableReports() {
return new List<ConcreteReport>(); // This doesnt work
}
IReport GetReport(int id){
return new ConcreteReport(); // But this works
}
}
It's because of covariance. You can get it to work in .NET 4 (read the link).
Try change to this
IList<? extends IReport> GetAvailableReports()
I recently ran into this problem myself, and found that using IEnumerable instead of List solves the problem. It was quite a frustrating issue, but once I found the source of the problem, it made sense.
Here's the test code I used to find the solution:
using System.Collections.Generic;
namespace InheritList.Test
{
public interface IItem
{
string theItem;
}
public interface IList
{
IEnumerable<IItem> theItems; // previously has as list... didn't work.
// when I changed to IEnumerable, it worked.
public IItem returnTheItem();
public IEnumerable<IItem> returnTheItemsAsList();
}
public class Item : IItem
{
string theItem;
}
public class List : IList
{
public IEnumerable<IItem> theItems; // List here didn't work - changed to IEnumerable
public List()
{
this.theItems = returnTheItemsAsList();
}
public IItem returnTheItem()
{
return new Item();
}
public IEnumerable<IItem> returnTheItemsAsList()
{
var newList = new List<Item>();
return newList;
}
}
}