How to count the listed items? - c#

I have a txt file with infos about some mobile phones.
Type;Size;Color;New-OrUsed;Warrantee(month);Price(HUF)
iPhone SE;64;Gold;New;0;95000
iPhone 6S;64;Silver;New;3;130000
iPhone 5S;16;Black;New;5;60000
iPhone 5S;32;Gold;New;6;75000
iPhone 5S;32;RoseGold;New;8;66500
iPhone 7;32;Black;Used;10;135000
iPhone X;256;Silver;New;12;400000
iPhone 6S;128;Silver;New;3;173000
iPhone 8;128;Gold;New;12;256000
iPhone 7;64;Red;Used;4;155000
iPhone 8 Plus;64;Silver;New;4;285000
iPhone 6S Plus;64;Black;Used;8;180000
iPhone 7 Plus;32;Red;Used;6;192000
I would like to list all of them, like below:
Type (Only once, whatever how many of them);How many does the text have of this type; how many color does the text have of this type
iPhone 5S;3;3
I could list the types with a hashset, but I have no idea how to count the different colors, and the number of the type.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
namespace nyilvantartas
{
class Program
{
struct adatok
{
public string tipus, szin, allapot;
public int meret, garancia, ar;
}
static void Main(string[] args)
{
StreamReader f = new StreamReader("termekek.txt", Encoding.Default);
HashSet<string> tipusok = new HashSet<string>();
List<int> hanyvan = new List<int>();
string[] hanyvann = new string[20];
string s;
string[] ss = new string[4];
adatok[] adatok = new adatok[1000];
int db = 0;
s = f.ReadLine();
while (!f.EndOfStream)
{
s = f.ReadLine();
ss = s.Split(';');
adatok[db].tipus = ss[0];
adatok[db].meret = int.Parse(ss[1]);
adatok[db].szin = ss[2];
adatok[db].allapot = ss[3];
adatok[db].garancia = int.Parse(ss[4]);
adatok[db].ar = int.Parse(ss[5]);
db++;
}
f.Close();
int ezustar = 0, gari=0;
double legolcsobb = 500000,legdragabb=0;
for (int i = 0; i < db; i++)
{
tipusok.Add(adatok[i].tipus);
if (adatok[i].szin=="Silver")
{
ezustar += adatok[i].ar;
}
if (adatok[i].ar>legdragabb)
{
legdragabb = adatok[i].ar;
}
if (adatok[i].ar<legolcsobb)
{
legolcsobb = adatok[i].ar;
}
gari += adatok[i].garancia;
}
legdragabb /= legolcsobb;
gari /= db;
string[] tipusokk = new string[13];
for (int i = 0; i < db; i++)
{
tipusok.Add(adatok[i].tipus);
}
for (int i = 0; i < db; i++)
{
hanyvann[i] = adatok[i].tipus;
}
Console.WriteLine("2.Feladat: {0} db iPhone található a listában.",+db);
Console.WriteLine("3.Feladat: Az összes ezüst színű készülék {0} Ft-ba kerülne",+ezustar);
Console.WriteLine("4.Feladat:");
foreach (var item in tipusok)
{
Console.WriteLine(item);
}
Console.WriteLine("5.Feladat: Átlagossan {0} hónap garanciát kapunk",gari);
Console.WriteLine("6.Felaadat: {0}-szor kerül többe a legdrágább a legolcsóbbnál.",legdragabb);
Console.ReadKey();
}
}
}

Create a class to hold the phone information:
class PhoneInfo {
public string type;
public int size;
public string Color;
public string newOrUsed;
public int warrantyMonth;
public decimal price;
}
Read in the text file and create a List of objects. I would suggest reading about String.Split.
List<PhoneInfo> phones;
Use LINQ to query the List.
var phoneCounts = from p in phones
group p by p.type into pg
select new {
type,
countOfType = pg.Count(),
countOfColors = pg.Select(p => p.color).Distinct().Count()
};

I could not open the link you sent, you can use hashset or any other data structure, but i prefer to use anonymous data,even you can build your own class and parse your data.
var rawData = System.IO.File.ReadAllText("aa.txt");
var data = rawData.Split(new[] {Environment.NewLine}, StringSplitOptions.None).Select(k =>
{ var segments = k.Split(';');
return new
{
Type = segments[0],
Size = segments[1],
Color = segments[2],
IsNew = segments[3],
Warranty = segments[4],
Price = segments[5]
};});
var report = data.GroupBy(k => k.Type).Select(p =>
new
{
Type = p.Key,
TypesCount = p.Count(),
ColorVarityCount = p.Select(o => o.Color).Distinct().Count()
});

Related

Weighted Job Scheduler - Retrieve Job Details

I am learning C# and want to created a weighted job scheduler.
The max profit is working fine. But I need to be able to get the JobIDs associated with it so I am trying to save it in an array jobsId, similar to this implementation in C++: https://onlinegdb.com/a9wx3nHoN.
But then in this snippet, I am getting an error: Wrong number of indices inside []; expected 2
if (profitSum > dp[i-1]) {
dp[i] = profitSum;
jobsId[i,0] = jobsId[task]; // Problem is here
jobsId[i].Append(jobs[i].id).ToArray(); //And here
}
What am I doing wrong? Please help, thanks!
Codes can be accessed here:
https://rextester.com/NXM85235
Alternatively, here is my entire snippet:
using System.IO;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
class Program
{
public int JobScheduling(int[] startTime, int[] endTime, int[] profit) {
var jobs = startTime
.Select((_, i) => new // create custom obj
{
id = i,
s = startTime[i],
e = endTime[i],
p = profit[i],
}
)
.OrderBy(x => x.e) // sort by end-time
.ToArray();
int[] dp = new int[jobs.Length];
int [,] jobsId = new int[,] {{jobs[0].id}};
int profitSum = jobs[0].p;
int task = -1;
dp[0] = jobs[0].p;
for (var i = 1; i < jobs.Length; i++) {
for (var j = i-1; j >= 0; j--) {
if (jobs[j].e <= jobs[i].s) {
task = j;
break;
}
}
if (task != -1) {
profitSum += dp[task];
}
if (profitSum > dp[i-1]) {
dp[i] = profitSum;
jobsId[i,0] = jobsId[task]; // Problem is here
jobsId[i].Append(jobs[i].id).ToArray();
}
}
// Need to implement this
for (var iter = 0; iter < jobsId.Length; iter++) {
Console.WriteLine(jobsId[iter,0]);
}
return dp[jobs.Length-1];
}
public static void Main(string[] args)
{
int[] startTime = { 1,3,6,2 };
int[] endTime = { 2,5,7,8 };
int[] profit = { 50,20,100,200 };
// Creating object
Program job = new Program();
Console.WriteLine(job.JobScheduling(startTime, endTime, profit));
}
}
int [,] jobsId = new int[,] {{jobs[0].id}};
The multi-dimensional 3d array that you are using has a fixed size .i.e. only one. You can't add any more elements to that array. Instead, try using List< List < int > >.
jobsId[i,0] = jobsId[task]; // problem here
Here jobsId is a 2d-array. You can't access the individual rows. You can only access elements within. For this too you need to create an array of array .i.e List< List < int > >.
And I could not figure out why are trying to get an array here.
jobsId[i].Append(jobs[i].id).ToArray();

Random.Next - Am I silently creating new instances?

Random.Next() randomness failures are almost always caused by creating and then using multiple instances of System.Random with the same seed, either with a time seed or a manual one. However, this is the only instance creation code in my class:
System.Random rNG;
if (string.IsNullOrEmpty(Map.Seed))
{
rNG = new System.Random();
}
else
{
rNG = new System.Random(Map.Seed.GetHashCode());
}
Looping through this second attempt code correctly creates random numbers:
var resourceRoll = rNG.Next(0, this.ResourceByRoll.Count);
var resourceRow = from row in this.ProcGenResourceTable.AsEnumerable()
.Where(row => row["Resource"].Equals(
this.ResourceByRoll[resourceRoll]
))
Looping through this original attempt code often creates the same number twice in a row:
var resourceRow = from row in this.ProcGenResourceTable.AsEnumerable()
.Where(row => row["Resource"].Equals(
this.ResourceByRoll[rNG.Next(0, this.ResourceByRoll.Count)]
))
Am I somehow silently creating a new instance of System.Random when using a Random.Next call as a dictionary index? Why does my original code often return the same number twice in a row?
If it matters:
This class is a Unity script
I am using System.Random, not UnityEngine.Random
My complete class is below:
using Assets.Code.Tools;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using UnityEngine;
public class Map : MonoBehaviour
{
public static int Length { get; set; }
public static int Width { get; set; }
public static int ResourceChanceDenominator { get; set; }
public static string Seed { get; set; }
private static int[,] objectGrid;
private DataTable ProcGenResourceTable { get; set; }
private Dictionary<int, string> ResourceByRoll { get; set; }
private List<GameObject> prefabTrees;
private List<GameObject> prefabStones;
private void Start()
{
this.prefabTrees = GeneralTools.GetPrefabsWithTag("Tree");
this.prefabStones = GeneralTools.GetPrefabsWithTag("Stone");
GenerateMap();
}
public void GenerateMap()
{
var procGenResourceTable = Resources.Load("ProcGenResourceTable") as TextAsset;
if (procGenResourceTable != null)
{
this.ProcGenResourceTable = GeneralTools.GetDataTableFromCSV(procGenResourceTable, "|", true, false);
}
else
{
Console.WriteLine("ProcGenResourceTable could not be found");
return;
}
Map.objectGrid = new int[Map.Width, Map.Length];
this.ResourceByRoll = GetPopulatedResourceByRollDictionary();
System.Random rNG;
if (string.IsNullOrEmpty(Map.Seed))
{
rNG = new System.Random();
}
else
{
rNG = new System.Random(Map.Seed.GetHashCode());
}
for (var i = 0; i < Map.Length; i++)
{
for (var j = 0; j < Map.Width; j++)
{
var roll = rNG.Next(Map.ResourceChanceDenominator);
if (roll == 1)
{
// var resourceRoll = rNG.Next(0, this.ResourceByRoll.Count);
var resourceRow = from row in this.ProcGenResourceTable.AsEnumerable()
.Where(row => row["Resource"].Equals(
this.ResourceByRoll[rNG.Next(0, this.ResourceByRoll.Count)]
))
select new
{
ModelFamily = row["Model Family"],
Tags = row["Tags"]
};
foreach (var row in resourceRow)
{
GameObject resource = null;
switch (row.ModelFamily)
{
case "Tree":
resource = Instantiate(this.prefabTrees[rNG.Next(this.prefabTrees.Count - 1)], new Vector3(i, 0, j), new Quaternion());
break;
case "Stone":
resource = Instantiate(this.prefabStones[rNG.Next(this.prefabStones.Count - 1)], new Vector3(i, 0, j), new Quaternion());
break;
default:
resource = Instantiate(this.prefabTrees[rNG.Next(this.prefabTrees.Count - 1)], new Vector3(i, 0, j), new Quaternion());
break;
}
var tagsListForResource = row.Tags.ToString().Split(new char[] { '|' }).ToList();
if (tagsListForResource.Contains("Resource"))
{
resource.tag = "Resource";
}
}
}
}
}
}
private Dictionary<int, string> GetPopulatedResourceByRollDictionary()
{
var resourceByRoll = new Dictionary<int, string>();
foreach (DataRow row in this.ProcGenResourceTable.Rows)
{
if (!string.IsNullOrEmpty(row["Weight"].ToString()))
{
for (var i = 0; i < Convert.ToInt32(row["Weight"]); i++)
{
resourceByRoll.Add(resourceByRoll.Count, row["Resource"].ToString());
}
}
}
return resourceByRoll;
}
}
I misunderstood what was going on - this is not related to repeated random numbers.
The answer to Michael Welch's question is that I am seeing trees and rocks generate on the same coordinates.
I expected this code to only generate one row of results:
var resourceRow = from row in this.ProcGenResourceTable.AsEnumerable()
.Where(row => row["Resource"].Equals(
this.ResourceByRoll[rNG.Next(0, this.ResourceByRoll.Count)]
))
However, it is sometimes returns more, because .Where() does some looping of its own that re-rolls the number each time.
Having multiple rows returned causes the foreach block to generate multiple prefabs at the coordinate instead of just one.

How to read 2D int array from binary file in c#?

I have a 2D integer array to store x,y coordinates. I checked out a few functions to write 2D array into a file but cannot find anything that is able to read that binary file on load and push it into a new 2 dimensional integer array.
This is my world generator function which saves it to the file:
public WorldGenerator()
{
int worldSizeX = 100;
int worldSizeY = 100;
int[,] world = new int[worldSizeX*worldSizeY, 2];
Logger.log("Generating world...");
for(int x = 0; x < worldSizeX; x++)
{
for(int y = 0; y < 2; y++)
{
System.Random random = new System.Random();
int itemID = random.Next(0, 1);
world[x, y] = itemID;
}
}
FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ConsoleGame/world/default.wd", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
for (int x = 0; x < worldSizeX; x++)
{
for (int y = 0; y < 2; y++)
{
bw.Write(world[x, y]);
}
}
bw.Close();
fs.Close();
Logger.log("World generated.");
}
Any good idea that could work for reading this file in? I should get back a 2D integer array and world[0,0] should get me the itemid. I am new to c# and this would be just a basic console application.
I have also seen others answering similar questions but none of them are worked for me yet. Maybe because this save function is wrong or something else.
EDIT:
Here is how I load the file:
using (var filestream = File.Open(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ConsoleGame/world/default.wd", FileMode.Open))
using (var binaryStream = new BinaryReader(filestream))
{
while (binaryStream.PeekChar() != -1)
{
Console.WriteLine(binaryStream.ReadInt32());
}
}
need Newtonsoft.Json
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ConsoleApp18
{
class Program
{
static void Main(string[] args)
{
int worldSizeX = 100;
int worldSizeY = 100;
int[,] world = new int[worldSizeX * worldSizeY, 2];
System.Random random = new System.Random();
for (int x = 0; x < worldSizeX; x++)
{
for (int y = 0; y < 2; y++)
{
int itemID = random.Next(0, 2);
world[x, y] = itemID;
}
}
string json = JsonConvert.SerializeObject(world, Formatting.Indented);
System.IO.File.WriteAllText("WriteText.txt", json);
string text = System.IO.File.ReadAllText("WriteText.txt");
int[,] deserialized = JsonConvert.DeserializeObject<int[,]>(text);
//use "deserialized"
}
}
}
What you need is called "Serialization".
Start with the simple builtin binary serializer.
Serializable attribute does the magic here.
By the moment you'll realize it is not the best option, you'll be able to use something more suiting your needs, like proto-buf.
I've also changed ints to shorts in your example. I doubt you need 32 bits for each world cell, so we can save a bit of hard drive space.
[Serializable]
public class WorldState
{
public short[,] Items { get; set; }
public void Save(string filename)
{
if (filename == null) throw new ArgumentNullException(nameof(filename));
using (var file = File.Create(filename))
{
var serializer = new BinaryFormatter();
serializer.Serialize(file, this);
}
}
public static WorldState Load(string filename)
{
if (filename == null) throw new ArgumentNullException(nameof(filename));
if (!File.Exists(filename)) throw new FileNotFoundException("File not found", filename);
using (var file = File.OpenRead(filename))
{
var serializer = new BinaryFormatter();
return serializer.Deserialize(file) as WorldState;
}
}
}
public class WorldStateTests
{
[Fact]
public void CanSaveAndLoad()
{
var ws = new WorldState
{
Items = new short[,]
{
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 }
}
};
// save the world state to file. Find it and see what's inside
ws.Save("./ws.bin");
// load the world back
var loaded = WorldState.Load("./ws.bin");
// check a new world state got loaded
Assert.NotNull(loaded);
// and it still has items
Assert.NotEmpty(loaded.Items);
// and the items are the same as we saved
Assert.Equal(ws.Items, loaded.Items);
}
}

How to sort list of strings of numbers in c# [duplicate]

I have a list of strings of version (see photo), and I'd like to sort them in descending order.
I've seen a few solutions using Version class to compare them, but I can't think of any solution that sort a whole list like this. What is the least complicated way to achieve this?
what is wrong with this simple implementation?
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var ver = new List<Version>();
ver.Add(new Version("3.5"));
ver.Add(new Version("3.15"));
ver.Add(new Version("3.10"));
ver.Add(new Version("3.1"));
ver.Sort();
ver.Reverse();
}
}
}
you can use IComparable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<string> data = new List<string>{
"3.5.0.1", "3.4.1.9", "3.4.1.56", "3.4.1.55", "3.4.1.46",
"3.4.1.45", "3.4.1.44", "3.4.1.30", "3.4.1.3", "3.4.1.22",
"3.4.1.2", "3.4.1.11", "3.4.1.0", "3.4.0.7", "3.4.0.3",
"3.4.0.1", "3.3.0.8", "3.3.0.4", "3.3.0.0", "3.2.0.9",
"3.2.0.6", "3.2.0.3", "3.2.0.27", "3.2.0.20", "3.2.0.15",
"3.2.0.1", "3.2.0.0", "3.1.0.7", "3.1.0.15", "3.1.0.14"
};
List<SortPara> sortPara = data.Select(x => new SortPara(x)).ToList();
data = sortPara.OrderBy(x => x).Select(x => x.strNumbers).ToList();
data = sortPara.OrderByDescending(x => x).Select(x => x.strNumbers).ToList();
}
}
public class SortPara : IComparable<SortPara>
{
public List<int> numbers { get; set; }
public string strNumbers { get; set; }
public SortPara(string strNumbers)
{
this.strNumbers = strNumbers;
numbers = strNumbers.Split(new char[] { '.' }).Select(x => int.Parse(x)).ToList();
}
public int CompareTo(SortPara other)
{
int shortest = this.numbers.Count < other.numbers.Count ? this.numbers.Count : other.numbers.Count;
int results = 0;
for (int i = 0; i < shortest; i++)
{
if (this.numbers[i] != other.numbers[i])
{
results = this.numbers[i].CompareTo(other.numbers[i]);
break;
}
}
return results;
}
}
}
know its an old thread but the easiest way is:
//list with some version numbers as strings
var versionList = new List<string>()
{
"1.1.0",
"1.10.0",
"1.112.0",
}
versionList.OrderByDescending(x => Version.Parse(x));
output:
1.112.0
1.10.0
1.1.0
You should use IComparable as jdweng, just edit a bit to compare versions like "2.1.0.4" and "2.1":
public int CompareTo(SortPara other)
{
int shortest = this.numbers.Count < other.numbers.Count ? this.numbers.Count : other.numbers.Count;
int results = 0;
for (int i = 0; i < shortest; i++)
{
if (this.numbers[i] != other.numbers[i])
{
results = this.numbers[i].CompareTo(other.numbers[i]);
break;
}
}
if (results != 0)
return results;
if (this.numbers.Count > other.numbers.Count)
return 1;
else if (this.numbers.Count < other.numbers.Count)
return -1;
else
return 0;
}
Here's a solution that will sort Semantic Versioning (https://semver.org). Nuget.Core offers a SemanticVersion class that operates very similarly to the standard Version class in .net. It will parse your string into an IComparable and IEquatable object so you can compare multiple versions or sort them within a collection, etc.
Nuget.Core: https://www.nuget.org/packages/nuget.core/ (you can pull this library via nuget)
https://github.com/NuGet/NuGet2/blob/2.13/src/Core/SemanticVersion.cs
var rawVersions = new [] {"v1.4.0", "v1.4.0-patch10", "v1.4.0-patch2"};
var versions = rawVersions.Select(v => new SemanticVersion(v));
var sorted = versions.ToList().Sort();
Sorry for late answer. we can sort version number this way too. here is a small example.
var ver = new List<string>();
ver.Add("3.5");
ver.Add("3.15");
ver.Add("3.10");
ver.Add("3.1");
var OrderData = ver.Select(x => new
{
version = x.ToString(),
vorder = x.ToString().Replace(".", "")
}).OrderByDescending(y => Convert.ToInt32(y.vorder)).ToList();

How to sort a list<string> / array of string version number?

I have a list of strings of version (see photo), and I'd like to sort them in descending order.
I've seen a few solutions using Version class to compare them, but I can't think of any solution that sort a whole list like this. What is the least complicated way to achieve this?
what is wrong with this simple implementation?
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var ver = new List<Version>();
ver.Add(new Version("3.5"));
ver.Add(new Version("3.15"));
ver.Add(new Version("3.10"));
ver.Add(new Version("3.1"));
ver.Sort();
ver.Reverse();
}
}
}
you can use IComparable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<string> data = new List<string>{
"3.5.0.1", "3.4.1.9", "3.4.1.56", "3.4.1.55", "3.4.1.46",
"3.4.1.45", "3.4.1.44", "3.4.1.30", "3.4.1.3", "3.4.1.22",
"3.4.1.2", "3.4.1.11", "3.4.1.0", "3.4.0.7", "3.4.0.3",
"3.4.0.1", "3.3.0.8", "3.3.0.4", "3.3.0.0", "3.2.0.9",
"3.2.0.6", "3.2.0.3", "3.2.0.27", "3.2.0.20", "3.2.0.15",
"3.2.0.1", "3.2.0.0", "3.1.0.7", "3.1.0.15", "3.1.0.14"
};
List<SortPara> sortPara = data.Select(x => new SortPara(x)).ToList();
data = sortPara.OrderBy(x => x).Select(x => x.strNumbers).ToList();
data = sortPara.OrderByDescending(x => x).Select(x => x.strNumbers).ToList();
}
}
public class SortPara : IComparable<SortPara>
{
public List<int> numbers { get; set; }
public string strNumbers { get; set; }
public SortPara(string strNumbers)
{
this.strNumbers = strNumbers;
numbers = strNumbers.Split(new char[] { '.' }).Select(x => int.Parse(x)).ToList();
}
public int CompareTo(SortPara other)
{
int shortest = this.numbers.Count < other.numbers.Count ? this.numbers.Count : other.numbers.Count;
int results = 0;
for (int i = 0; i < shortest; i++)
{
if (this.numbers[i] != other.numbers[i])
{
results = this.numbers[i].CompareTo(other.numbers[i]);
break;
}
}
return results;
}
}
}
know its an old thread but the easiest way is:
//list with some version numbers as strings
var versionList = new List<string>()
{
"1.1.0",
"1.10.0",
"1.112.0",
}
versionList.OrderByDescending(x => Version.Parse(x));
output:
1.112.0
1.10.0
1.1.0
You should use IComparable as jdweng, just edit a bit to compare versions like "2.1.0.4" and "2.1":
public int CompareTo(SortPara other)
{
int shortest = this.numbers.Count < other.numbers.Count ? this.numbers.Count : other.numbers.Count;
int results = 0;
for (int i = 0; i < shortest; i++)
{
if (this.numbers[i] != other.numbers[i])
{
results = this.numbers[i].CompareTo(other.numbers[i]);
break;
}
}
if (results != 0)
return results;
if (this.numbers.Count > other.numbers.Count)
return 1;
else if (this.numbers.Count < other.numbers.Count)
return -1;
else
return 0;
}
Here's a solution that will sort Semantic Versioning (https://semver.org). Nuget.Core offers a SemanticVersion class that operates very similarly to the standard Version class in .net. It will parse your string into an IComparable and IEquatable object so you can compare multiple versions or sort them within a collection, etc.
Nuget.Core: https://www.nuget.org/packages/nuget.core/ (you can pull this library via nuget)
https://github.com/NuGet/NuGet2/blob/2.13/src/Core/SemanticVersion.cs
var rawVersions = new [] {"v1.4.0", "v1.4.0-patch10", "v1.4.0-patch2"};
var versions = rawVersions.Select(v => new SemanticVersion(v));
var sorted = versions.ToList().Sort();
Sorry for late answer. we can sort version number this way too. here is a small example.
var ver = new List<string>();
ver.Add("3.5");
ver.Add("3.15");
ver.Add("3.10");
ver.Add("3.1");
var OrderData = ver.Select(x => new
{
version = x.ToString(),
vorder = x.ToString().Replace(".", "")
}).OrderByDescending(y => Convert.ToInt32(y.vorder)).ToList();

Categories

Resources