c# how to sort nested collections - c#

I am probably overthinking this all and I'm lost. I'm new to C# and don't know what is the best way to solve this.
string[] input = new string { "FR_Paris", "UK_London", "UK_Bristol" };
Desirable output in console is ordered by occurrence of cities in a country and cities are sorted alphabetically.
In this situation it is:
UK 2x Bristol, London
FR 1x Paris
I'm not going to lie, this is my homework. I know how to parse the input and I think for cities has to be used a collection which can be sorted but don't know which type. I'm kind of lost when it comes to nested collections.
Please give me at least a direction.
Thanks a lot!

Try This
// Init Array
string[] input = new string[] { "FR_Paris", "UK_London", "UK_Bristol" };
//Get All Codes
List<string> Codes = new List<string>();
foreach (var CityName in input)
{
var Name = CityName.Split('_')[0]; // Get Name After _ Paris
if (!Codes.Contains(Name))
Codes.Add(va);
}
// Print
foreach (var Code in Codes.OrderBy(x => x))
{
var AllNames = input.Where(x => x.StartsWith(Code + "_")).Select(x => x.Split('_')[1]);
Console.WriteLine(Code + " " + xd.Count() + "x " + string.Join(",", AllNames.OrderBy(x => x)));
}

You can try with linq
var input = new List<string> { "FR_Paris", "UK_London", "UK_Bristol" };
var result = input.Select(x => new { Country = x.Split("_")[0], City = x.Split("_")[1] })
.GroupBy(x => x.Country)
.Select(x => $"{x.Key} {x.Count()}x {String.Join(", ", x.OrderBy(x => x.City).Select(x => x.City))} ");
foreach (var item in result)
{
Console.WriteLine(item);
}
OUTPUT
FR 1x Paris
UK 2x Bristol, London

Using LINQ:
var grouped = input
.Select(x => x.Split('_')) // Split all strings into array[2]
.GroupBy(x => x[0]) // Group by country
.OrderByDecending(x => x.Count()); // Order by number of cities

Related

A better way to count and sort by frequency?

I have a string liste like this
title1;duration1
title2;duration2
title1;duration3
Which means that the title was shown for duration milliseconds to be replaced by the next title for the next duration.
title can repeat itself.
The goal is to look for each title that is the same, to then add its duration to then create a list of all distinct titles sorted descendingly by their sum of durations.
My approach:
string[] units = liste.split('\n');
Dictionary<string, long> d = new Dictionary<string, long>();
foreach(var row in units)
{
string[] e = row.split(';');
//if e[0] in d => add e[1] to d[e[0]] else set d[e[0]] to e[1]
}
//Convert d to list and sort descendingly by long.
Is there a better way?
I'm not necessarily suggesting this is the best way because it is kind of incomprehensible and maintainable code is important, but you can obtain your result in a single statement with LINQ. This solution assumes you have confidence in your data being clean - meaning no blank values or values that don't convert to double, etc.
split the string on newline
project an object for each line and substring at ";"
Group by title
project again into a new list that sums the groupings
Finally sort the list.
string liste = #"title1;8.91
title2; 3
title1; 4.5";
var result = liste.Split('\n')
.Select(l => new {
title = l.Substring(0, l.IndexOf(';')).Trim(),
duration = l.Substring(l.IndexOf(';')+1, l.Length - (l.IndexOf(';')+1)).Trim()
})
.GroupBy(l => l.title)
.Select(l => new { title = l.Key, durations = l.Sum(m => double.Parse(m.duration))})
.OrderByDescending(l => l.durations);
Use linq :
string input = "title1;10\n" +
"title2;20\n" +
"title1;30";
var rows = input.Split(new char[] {'\n'}).Select(x => x.Split(new char[] {';'})).Select(y => new {title = y.First(), duration = int.Parse(y.Last())}).ToList();
var sums = rows.GroupBy(x=> x.title).Select(x => new {title = x.Key, duration = x.Sum(y => y.duration)}).ToList();

Split the string and join all first elements then second element and so on in c#

I have a string like this -
var roleDetails = "09A880C2-8732-408C-BA09-4AD6F0A65CE9^Z:WB:SELECT_DOWNLOAD:0000^Product Delivery - Download^1,24B11B23-1669-403F-A24D-74CE72DFD42A^Z:WB:TRAINING_SUBSCRIBER:0000^Training Subscriber^1,6A4A6543-DB9F-46F2-B3C9-62D69D28A0B6^Z:WB:LIC_MGR_HOME_REDL:0000^License Manager - Home use^1,76B3B165-0BB4-4E3E-B61F-0C0292342CE2^Account Admin^Account Admin^1,B3C0CE51-00EE-4A0A-B208-98653E21AE11^Z:WB:1BENTLEY_ISA_ADMIN:0000^Co-Administrator^1,CBA225BC-680C-4627-A4F6-BED401682816^ReadOnly^ReadOnly^1,D80CF5CF-CB6E-4424-9D8F-E29F96EBD4C9^Z:WB:MY_SELECT_CD:0000^Product Delivery - DVD^1,E0275936-FBBB-4775-97D3-9A7D19D3E1B4^Z:WB:LICENSE_MANAGER:0000^License Manager^1";
Spliting it with "," returns this -
[0] "09A880C2-8732-408C-BA09-4AD6F0A65CE9^Z:WB:SELECT_DOWNLOAD:0000^Product Delivery - Download^1"
[1] "24B11B23-1669-403F-A24D-74CE72DFD42A^Z:WB:TRAINING_SUBSCRIBER:0000^Training Subscriber^1"
[2] "6A4A6543-DB9F-46F2-B3C9-62D69D28A0B6^Z:WB:LIC_MGR_HOME_REDL:0000^License Manager - Home use^1"
[3] "76B3B165-0BB4-4E3E-B61F-0C0292342CE2^Account Admin^Account Admin^1"
[4] "B3C0CE51-00EE-4A0A-B208-98653E21AE11^Z:WB:1BENTLEY_ISA_ADMIN:0000^Co-Administrator^1"
[5] "CBA225BC-680C-4627-A4F6-BED401682816^ReadOnly^ReadOnly^1"
[6] "D80CF5CF-CB6E-4424-9D8F-E29F96EBD4C9^Z:WB:MY_SELECT_CD:0000^Product Delivery - DVD^1"
[7] "E0275936-FBBB-4775-97D3-9A7D19D3E1B4^Z:WB:LICENSE_MANAGER:0000^License Manager^1"
All elements contains carat (^). so spliting each element further with ^ symbol will return four element.
But I want to join all first element then all second element and then third and so on and get the result like this -
[0]: 09A880C2-8732-408C-BA09-4AD6F0A65CE9, 24B11B23-1669-403F-A24D-74CE72DFD42A, 6A4A6543-DB9F-46F2-B3C9-62D69D28A0B6, 76B3B165-0BB4-4E3E-B61F-0C0292342CE2, B3C0CE51-00EE-4A0A-B208-98653E21AE11, CBA225BC-680C-4627-A4F6-BED401682816, D80CF5CF-CB6E-4424-9D8F-E29F96EBD4C9, E0275936-FBBB-4775-97D3-9A7D19D3E1B4
[1]: Z:WB:SELECT_DOWNLOAD:0000,Z:WB:TRAINING_SUBSCRIBER:0000, Z:WB:LIC_MGR_HOME_REDL:0000,Account Admin, Z:WB:1BENTLEY_ISA_ADMIN:0000, ReadOnly, Z:WB:MY_SELECT_CD:0000, Z:WB:LICENSE_MANAGER
[2]: Product Delivery - Download, Training Subscriber, License Manager - Home use, Account Admin, Co-Administrator, ReadOnly, Product Delivery - DVD, License Manager
[3]: 1,1,1,1,1,1,1,1
What is the quickest and simplest way of achieving this?
EDIT
This is what I tried so far -
var rolearray = roleDetails.Split(',').Select(s => s.Split('^')).Select(a => new { RoleId = a[0], RoleNme = a[1], FriendlyName = a[2], IsUserInRole = a[3] });
but again this is not returning the way I need it. But I want to join all a[0]s , then all a[1] and so on
SOLUTION:
After comparing solutions and ran it 10 times in a loop to see the performance I found solution suggested by Jamiec is taking less time. So selecting this solution.
Pure LINQ solution:
roleDetails.Split(',')
.SelectMany(x => x.Split('^').Select((str, idx) => new {str, idx}))
.GroupBy(x => x.idx)
.Select(grp => string.Join(", ", grp.Select(x => x.str)))
The easiest way to do this, is to simply do:
var split = roleDetails.Split(',')
.Select(x => x.Split('^').ToArray())
.ToArray();
You would then access the elements like a multi dimensional jagged array
Console.WriteLine(split[0][0]);
// result: 09A880C2-8732-408C-BA09-4AD6F0A65CE9
Live example: http://rextester.com/NEUVOR15080
And if you then want all the elements grouped
Console.WriteLine(String.Join(",",split.Select(x => x[0])));
Console.WriteLine(String.Join(",",split.Select(x => x[1])));
Console.WriteLine(String.Join(",",split.Select(x => x[2])));
Console.WriteLine(String.Join(",",split.Select(x => x[3])));
Live example: http://rextester.com/BZXLG67151
Here you can user Aggregate and Zip extension method of Linq.
Aggregate: Performs a specified operation to each element in a collection, while carrying the result forward.
Zip: The Zip extension method acts upon two collections. It processes each element in two series together.
var roleDetails = "09A880C2-8732-408C-BA09-4AD6F0A65CE9^Z:WB:SELECT_DOWNLOAD:0000^Product Delivery - Download^1,24B11B23-1669-403F-A24D-74CE72DFD42A^Z:WB:TRAINING_SUBSCRIBER:0000^Training Subscriber^1,6A4A6543-DB9F-46F2-B3C9-62D69D28A0B6^Z:WB:LIC_MGR_HOME_REDL:0000^License Manager - Home use^1,76B3B165-0BB4-4E3E-B61F-0C0292342CE2^Account Admin^Account Admin^1,B3C0CE51-00EE-4A0A-B208-98653E21AE11^Z:WB:1BENTLEY_ISA_ADMIN:0000^Co-Administrator^1,CBA225BC-680C-4627-A4F6-BED401682816^ReadOnly^ReadOnly^1,D80CF5CF-CB6E-4424-9D8F-E29F96EBD4C9^Z:WB:MY_SELECT_CD:0000^Product Delivery - DVD^1,E0275936-FBBB-4775-97D3-9A7D19D3E1B4^Z:WB:LICENSE_MANAGER:0000^License Manager^1";
var rolearray = roleDetails.Split(',')
.Select(s => s.Split('^'))
.Aggregate((s1Array, s2Array) => s1Array.Zip(s2Array, (s1, s2) => s1 + "," + s2).ToArray());
string roleDetails = "09A880C2-8732-408C-BA09-4AD6F0A65CE9^Z:WB:SELECT_DOWNLOAD:0000^Product Delivery - Download^1,24B11B23-1669-403F-A24D-74CE72DFD42A^Z:WB:TRAINING_SUBSCRIBER:0000^Training Subscriber^1,6A4A6543-DB9F-46F2-B3C9-62D69D28A0B6^Z:WB:LIC_MGR_HOME_REDL:0000^License Manager - Home use^1,76B3B165-0BB4-4E3E-B61F-0C0292342CE2^Account Admin^Account Admin^1,B3C0CE51-00EE-4A0A-B208-98653E21AE11^Z:WB:1BENTLEY_ISA_ADMIN:0000^Co-Administrator^1,CBA225BC-680C-4627-A4F6-BED401682816^ReadOnly^ReadOnly^1,D80CF5CF-CB6E-4424-9D8F-E29F96EBD4C9^Z:WB:MY_SELECT_CD:0000^Product Delivery - DVD^1,E0275936-FBBB-4775-97D3-9A7D19D3E1B4^Z:WB:LICENSE_MANAGER:0000^License Manager^1";
var RawItems = roleDetails.Split(',').Select(x=> x.Split('^'));
var Items1 = RawItems.Select(x=> x.ElementAt(0));
var Items2 = RawItems.Select(x=> x.ElementAt(1));
var Items3 = RawItems.Select(x=> x.ElementAt(2));
var Items4 = RawItems.Select(x=> x.ElementAt(3));
If you don't like the LINQ solutions, here's a solution without:
var result = new string[4];
var i = 0;
foreach(var line in roleDetails.Split(','))
foreach(var piece in line.Split('^'))
result[i++ % 4] += (i <= 4 ? "" : ",") + piece;
Basically, you split on commas and carets, and foreach on each, using a counter that tells us which array element to concatenate in, and whether to use a comma separator or not.
If your initial string is much bigger than in this example, consider first creating an array of StringBuilders first as these are better performing with concatenations:
var stringBuilders = new StringBuilder[4];
var result = new string[4];
var i = 0;
for (var i = 0; i < 4; i++)
stringBuilders[i] = new StringBuilder();
foreach(var line in roleDetails.Split(','))
foreach(var piece in line.Split('^'))
stringBuilders[i++ % 4].Append((i <= 4 ? "" : ",") + piece);
foreach (var stringBuilder in stringBuilders)
result[i++ % 4] = stringBuilder.ToString();
One more LINQ solution. But not as clean as #Pavel's:
string a = "", b = "", c = "", d = "";
roleDetails.Split(',').ToList().ForEach(x =>
{
a += x.Split('^')[0] + ',';
b += x.Split('^')[1] + ',';
c += x.Split('^')[2] + ',';
d += x.Split('^')[3] + ',';
});
MessageBox.Show(a.Trim(','));
MessageBox.Show(b.Trim(','));
MessageBox.Show(c.Trim(','));
MessageBox.Show(d.Trim(','));
OUTPUT:
a = 09A880C2-8732-408C-BA09-4AD6F0A65CE9,24B11B23-1669-403F-A24D-74CE72DFD42A,6A4A6543-DB9F-46F2-B3C9-62D69D28A0B6,76B3B165-0BB4-4E3E-B61F-0C0292342CE2,B3C0CE51-00EE-4A0A-B208-98653E21AE11,CBA225BC-680C-4627-A4F6-BED401682816,D80CF5CF-CB6E-4424-9D8F-E29F96EBD4C9,E0275936-FBBB-4775-97D3-9A7D19D3E1B4
b = Z:WB:SELECT_DOWNLOAD:0000,Z:WB:TRAINING_SUBSCRIBER:0000,Z:WB:LIC_MGR_HOME_REDL:0000,Account Admin,Z:WB:1BENTLEY_ISA_ADMIN:0000,ReadOnly,Z:WB:MY_SELECT_CD:0000,Z:WB:LICENSE_MANAGER:0000
c = Product Delivery - Download,Training Subscriber,License Manager - Home use,Account Admin,Co-Administrator,ReadOnly,Product Delivery - DVD,License Manager
d = 1,1,1,1,1,1,1,1
Fairly clean and fast...
var sets = new[]
{
new List<string>(),
new List<string>(),
new List<string>(),
new List<string>(),
};
foreach (var role in roleDetails.Split(','))
{
var details = role.Split('^');
sets[0].Add(details[0]);
sets[1].Add(details[1]);
sets[2].Add(details[2]);
sets[3].Add(details[3]);
}
var lines = sets.Select(set => string.Join(",", set)).ToArray();
... little nuts to understand and doesn't really save anything on performance ...
var ret = roleDetails.Split(',')
.Aggregate(seed: new { SBS = new[] { new StringBuilder(), new StringBuilder(),
new StringBuilder(), new StringBuilder(), },
Start = true },
func: (seed, role) =>
{
var details = role.Split('^');
if (seed.Start)
{
seed.SBS[0].Append(details[0]);
seed.SBS[1].Append(details[1]);
seed.SBS[2].Append(details[2]);
seed.SBS[3].Append(details[3]);
return new
{
seed.SBS,
Start = false,
};
}
else
{
seed.SBS[0].Append(',').Append(details[0]);
seed.SBS[1].Append(',').Append(details[1]);
seed.SBS[2].Append(',').Append(details[2]);
seed.SBS[3].Append(',').Append(details[3]);
return seed;
}
},
resultSelector: result => result.SBS.Select(sb => sb.ToString()).ToArray()
);
You can use Tuple here
var roles = roleDetails.Split(',')
.Select(x => x.Split('^'))
.Where(x=>x.Length==4)
.Select(x=>
new Tuple<string, string, string, string>(x[0], x[1], x[2], x[3]))
.ToList();
var item1 = string.Join(",", roles.Select(x=>x.Item1).ToArray());
var item2 = string.Join(",", roles.Select(x => x.Item2).ToArray());
var item3 = string.Join(",", roles.Select(x => x.Item3).ToArray());
var item4 = string.Join(",", roles.Select(x => x.Item4).ToArray());
Your attempt tries to do everything in a single line, which is making it much harder for you to understand what's happening.
You're already using all the tools you need (Select() and Split()). If you make your code more readable by separating everything into separate lines of code, then it becomes much easier to find your way:
//Your data string
string myDataString = "...";
//Your data string, separated into a list of rows (each row is a string)
var myDataRows = myDataString.Split(',');
//Your data string, separated into a list of rows (each row is a STRING ARRAY)
var myDataRowsAsStringArrays = myDataRows.Select(row => row.Split('^'))
And now, all you need to do is retrieve the correct data.
var firstColumnValues = myDataRowsAsStringArrays.Select(row => row[0]);
var secondColumnValues = myDataRowsAsStringArrays.Select(row => row[1]);
var thirdColumnValues = myDataRowsAsStringArrays.Select(row => row[2]);
var fourthColumnValues = myDataRowsAsStringArrays.Select(row => row[3]);
And if you so choose, you can join the values into a single comma separated string:
var firstColumnString = String.Join(", ", firstColumnValues);
var secondColumnString = String.Join(", ", secondColumnValues);
var thirdColumnString = String.Join(", ", thirdColumnValues);
var fourthColumnString = String.Join(", ", fourthColumnValues);

Group string values

I have this code
var myBuilder = new StringBuilder();
foreach (var item in myList)
{
myBuilder.Append(item.Number).Append(" - ").Append(item.SecondNumber).Append(", ");
}
var text = myBuilder;
and using that I'm getting this text
AAA08 - BB08, AAA09 - BB09, AAA09 - BB10,
myList returns this:
{ Number = "AAA08", SecondNumber = "BB08" }
{ Number = "AAA09", SecondNumber = "BB09" }
{ Number = "AAA09", SecondNumber = "BB10" }
How can I concatenate it to string to display this:
AAA08 - BB08; AAA09 - BB09, BB10
I can do replace , to ; but can't get how to group these Numberto display only one and each SecondNumber right to him
You can do this with Linq and string.Join
var grouped = myList
.GroupBy(x => x.Number)
.Select(g => g.Key + " - " + string.Join(", ", g.Select(x => x.SecondNumber)))
var text = string.Join("; ", grouped);
You can use GroupBy and String.Join:
var groupedNumbers= myList
.GroupBy(x => x.Number)
.Select(g => $"{g.Key} - {String.Join(", ", g.Select(x => x.SecondNumber))}");
string result = String.Join("; ", groupedNumbers);
I'm using string interpolation which is a C#6 feature, if you aren't using it replace $"{g.Key}..." with String.Format("{0}...", g.Key, ..).
When you get Number, iterate through myList to find all instances of Number, then get each corresponding SecondNumber and append it to your string.
Before building final string you probably would need to group your array first with this code:
var groupedList = myList.GroupBy(x => x.Number)
and later use that grouped list to get proper string:
foreach (var item in groupedList)
{
myBuilder.Append(item.Number).Append(" - ").Append(item.Select(x => x.SecondNumber).Join(", ")).Append("; ");
}

Search list and order List by value max found c#

i like to confess that i am weak in LINQ.
i have list with data. i want to search list fist by given value and then sort data by max occurance means which comes maximum time in rows.
List<SearchResult> list = new List<SearchResult>() {
new SearchResult(){ID=1,Title="Cat"},
new SearchResult(){ID=2,Title="dog"},
new SearchResult(){ID=3,Title="Tiger"},
new SearchResult(){ID=4,Title="Cat"},
new SearchResult(){ID=5,Title="cat"},
new SearchResult(){ID=6,Title="dog"},
};
if i search & sort list with data like "dog cat" then output will be like
ID=1,Title=Cat
ID=4,Title=Cat
ID=5,Title=Cat
ID=2,Title=dog
ID=6,Title=dog
all cat will come first because this cat keyword found maximum time in all the rows and then dog found maximum time.
this below data will not come because it is not in search term
ID=3,Title=Tiger
looking for solution. thanks
UPDATE PORTION CODE
List<SearchResult> list = new List<SearchResult>() {
new SearchResult(){ID=1,Title="Geo Prism 1995 - ABS #16213899"},
new SearchResult(){ID=2,Title="Excavator JCB - ECU P/N: 728/35700"},
new SearchResult(){ID=3,Title="Geo Prism 1995 - ABS #16213899"},
new SearchResult(){ID=4,Title="JCB Excavator - ECU P/N: 728/35700"},
new SearchResult(){ID=5,Title="Geo Prism 1995 - ABS #16213899"},
new SearchResult(){ID=6,Title="dog"},
};
var to_search = new[] { "Geo", "JCB" };
var result = list.Where(sr => to_search.Any(ts => String.Compare(ts, sr.Title, StringComparison.OrdinalIgnoreCase) == 0))
.GroupBy(sr => sr.Title.ToLower())
.OrderByDescending(g => g.Count());
var matched = result.SelectMany(m => m);
var completeList = matched.Concat(list.Except(matched));
dataGridView2.DataSource = completeList.ToList();
i try to your logic in another apps but it is not working. according to logic three rows first come with GEO keyword and then next 2 rows comes with JCB and then unmatched rest comes. what i need to change in ur code. please help. thanks
This will filter your list and group it by Title, sorting the groups by their size.
List<SearchResult> list = new List<SearchResult>() {
new SearchResult(){ID=1,Title="Cat"},
new SearchResult(){ID=2,Title="dog"},
new SearchResult(){ID=3,Title="Tiger"},
new SearchResult(){ID=4,Title="Cat"},
new SearchResult(){ID=5,Title="cat"},
new SearchResult(){ID=6,Title="dog"},
};
var to_search = new[] { "cat", "dog" };
var result = list.Where(sr => to_search.Any(ts => String.Compare(ts, sr.Title, StringComparison.OrdinalIgnoreCase) == 0))
.GroupBy(sr => sr.Title.ToLower())
.OrderByDescending(g => g.Count());
foreach (var group in result)
foreach (var element in group)
Debug.WriteLine(String.Format("ID={0},Title={1}", element.ID, element.Title));
Output:
ID=1,Title=Cat
ID=4,Title=Cat
ID=5,Title=cat
ID=2,Title=dog
ID=6,Title=dog
If you don't care about the actual grouping, just can flatten the list of groups with SelectMany.
(Note that this code will ignore the case of Title. I don't know if this is what you want or if it is a typo in code: you are using cat and Cat, and in your output it is only Cat, but dog is not capitalized.)
Edit:
To get the unmatched items, you can use Except:
var unmatched = list.Except(result.SelectMany(m => m)); // beware! contains the tiger!
Edit 2:
var result = list.Where(sr => to_search.Any(ts => String.Compare(ts, sr.Title, StringComparison.OrdinalIgnoreCase) == 0))
.GroupBy(sr => sr.Title.ToLower())
.OrderByDescending(g => g.Count());
var matched = result.SelectMany(m => m);
var completeList = matched.Concat(list.Except(matched));
foreach (var element in completeList)
Debug.WriteLine(String.Format("ID={0},Title={1}", element.ID, element.Title));
Output
ID=1,Title=Cat
ID=4,Title=Cat
ID=5,Title=cat
ID=2,Title=dog
ID=6,Title=dog
ID=3,Title=Tiger
Edit 3
var result = from searchResult in list
let key_string = to_search.FirstOrDefault(ts => searchResult.Title.ToLower().Contains(ts.ToLower()))
group searchResult by key_string into Group
orderby Group.Count() descending
select Group;
IEnumerable<string> pets = new[] { "Cat", "dog", "Tiger", "Cat", "cat", "dog" };
var test = pets
.Where(p=>p.ToUpperInvariant() == "CAT" || p.ToUpperInvariant() == "DOG")
.GroupBy(p => p.ToUpperInvariant())
.OrderByDescending(g => g.Count())
.SelectMany(p => p);
foreach (string pet in test)
Console.WriteLine(pet);
I think the following should do the trick.
var searchText = "cat dog";
var searchResult = list
.Select(i => new {
Item = i,
Count = list.Count(x => string.Compare(x.Title, i.Title, true) == 0) // Add counter
})
.Where(i => searchText.Contains(i.Item.Title))
.OrderByDescending(i => i.Count)
.ThenBy(i => i.Item.ID)
.ToList()
Update
If you want unmatched data at the end, you need to add another sorting property in the anonymous object.
var searchText = "cat dog";
var searchResult = list
.Select(i => new {
Item = i,
Matched = searchText.Contains(i.Item.Title.ToUpper()),
Count = list.Count(x => string.Compare(x.Title, i.Title, true) == 0) // Add counter
})
.OrderByDescending(i => i.Matched)
.ThenBy(i => i.Count)
.ThenBy(i => i.Item.ID)
.ToList()

Getting a distinct list with addition of the totals

I have a list of string items declared like this:
List<string> methodList = new List<string>();
I do what I need to get done and the results are something like this:
Method1;15
Method2;30
Method3;45
Method1;60
I need to loop through this list and display a distinct list and the addition of the totals. Something like this:
Method1 75
Method2 30
Method3 45
In order to do this, you'll need to split this up, then sum:
var results = methodList
.Select(l => l.Split(';'))
.GroupBy(a => a[0])
.Select(g =>
new
{
Group = g.Key,
Count = g.Count(),
Total = g.Sum(arr => Int32.Parse(arr[1]))
});
foreach(var result in results)
Console.WriteLine("{0} {1} {2}", result.Group, result.Count, result.Total);
Something like this would work:
var sumList = methodList.Select( x=>
{
var parts = x.Split(';');
return new
{
Method = parts [0],
Cost = Convert.ToInt32(parts[1])
};
})
.GroupBy( x=> x.Method)
.Select( g=> new { Method = g.Key, Sum = g.Sum( x=> x.Cost) })
.ToList();
foreach(var item in sumList)
Console.WriteLine("Total for {0}:{1}", item.Method, item.Sum);
A better approach would be to keep the individual methods and their cost in a strongly typed class, so you don't have to do string parsing to operate them:
public class MethodCost
{
public string MethodName { get; set; }
public int Cost { get; set; }
}
Now you can use a List<MethodCost> instead and have direct access to the cost - use strings for presentation (i.e. writing to the console), not for internal storage when it is not appropriate.
Try the following
var result = methodList
.Select(
x =>
{
var items = x.Split(';');
return new { Name = items[0], Value = Int32.Parse(items[1]) };
})
.GroupBy(pair => pair.Name)
.Select(
grouping =>
{
var sum = grouping.Sum(x => x.Value);
return String.Format("{0} {1}", grouping.Key, sum);
});
Yet another, slightly compacter variant is
var results = from item in methodList
let parts = item.Split(';')
group Int32.Parse(parts[1]) by parts[0];
foreach(var item in results)
Console.WriteLine("{0} {1}", item.Key, item.Sum());

Categories