score:3
you could try this, although i have not performance tested it yet:
list<string> originallist = new list<string>()
{
@"aaa\bbb",
@"aaa\ccc",
@"aaa\ccc",
@"bbb\xxx",
@"bbb",
@"bbb\xxx",
@"bbb\xxx"
};
list<string> outputlist = new list<string>();
foreach(var g in originallist.groupby(x => x).select(x => x.tolist()))
{
var index = 1;
foreach(var item in g)
{
outputlist.add(string.format("{0}[{1}]", item, index++));
}
}
fiddle here
score:0
you could just use group() to pull the strings together and then project those groups using a combination of value and count.
given your list of strings:
var listofstrings;
var grouped = listofstrings.groupby(x => x);
var groupedcount = grouped.select(x => new {key = x.key, count = group.count()});
score:0
you can use this crisp and crunchy code:
public static void main()
{
var originallist = new list<string>()
{
@"aaa\bbb",
@"aaa\ccc",
@"aaa\ccc",
@"bbb\xxx",
@"bbb",
@"bbb\xxx",
@"bbb\xxx"
};
var outputlist = originallist.groupby(x => x).selectmany(x => x.select((y, i) => string.format("{0}[{1}]", y, i + 1)));
console.writeline(string.join("\n", outputlist));
}
score:0
using a hashset
note: dump() is a linqpad method that prints the results to the screen — substitute as necessary.
void main()
{
var list = new list<string> {"hello", "doctor", "name", "continue", "yesterday", "tomorrow", "hello"};
//case-insensitive string compare
list.hasduplicates(stringcomparer.ordinalignorecase).dump();
//case-sensitive string compare
list.hasduplicates().dump();
//integer compare
var list2 = new list<int> { 1,2,3,4,5,2 };
list2.hasduplicates().dump();
}
public static class test
{
public static bool hasduplicates<t>(this ilist<t> list, stringcomparer stringcomparer = null)
{
if (typeof(t) == typeof(string))
{
var hash = new hashset<string>(list.count, stringcomparer);
foreach (var val in list) if (!hash.add(val?.tostring())) break;
return hash.count != list.count;
}
else
{
var hash = new hashset<t>(list.count);
foreach (var val in list) if (!hash.add(val)) break;
return hash.count != list.count;
}
}
}
/*
output:
true
false
true
*/
score:1
what about this?
static ienumerable<string> mycounter(ienumerable<string> data)
{
var mydic = new dictionary<string, int>();
foreach (var d in data)
{
if (!mydic.containskey(d))
mydic[d] = 1;
else
mydic[d] = mydic[d] + 1 ;
yield return d +"[" + mydic[d] + "]";
}
}
score:1
you could iterate over the list and use a dictionary to get the count, like this:
private int getcount(idictionary<string, int> counts, string item)
{
int count;
if (!counts.trygetvalue(item, out count))
count = 0;
count++;
counts[item] = count;
return count;
}
private ienumerable<string> getitems(ienumerable<string> items)
{
// initialize dict for counts with appropriate comparison
var counts = new dictionary<string, int>(stringcomparer.ordinalignorecase);
foreach(var item in items)
yield return string.format("{0}[{1}]", item, getcount(counts, item));
}
score:10
since you ask for fastest, the best imo would be to use foreach
loop and counting dictionary<string, int>
. it has the same time complexity as hashset
and uses much less memory than linq groupby
:
var counts = new dictionary<string, int>(pathlist.count); // specify max capacity to avoid rehashing
foreach (string item in pathlist)
{
// do some stuff here and pick 'item' only if it fits some criteria.
if (isvalid(item))
{
int count;
counts.trygetvalue(item, out count);
counts[item] = ++count;
duplicateitems.add(item + "[" + count + "]");
}
}
Source: stackoverflow.com
Related Query
- Fastest way to find duplicate items in a list in C#
- Fastest way to get matching items from two list c#
- Find duplicate items in list based on particular member value
- C# LINQ Find List Inside Another List, Better way to code this than a foreach loop
- What's the fastest way to find and delete duplicate nodes inside XML?
- The fastest way to find dictionary keys that are not exist in another list
- Fastest way for Linq to find duplicate Lists?
- How to get duplicate items from a list using LINQ?
- LINQ query to find if items in a list are contained in another list
- How to find List has duplicate values in List<string>
- LINQ - Find all items in one list that aren't in another list
- Find items from a list which exist in another list
- LINQ way to get items between two indexes in a List
- Find all items whose collection property contains items in another list
- How to generate duplicate items in a list using LINQ?
- Whats the 'modern' way to find common items in two Lists<T> of objects?
- How to find duplicate items in list<>?
- Create duplicate items in a list
- How to find duplicate items based on multiple values using LINQ?
- Is there a better way to set a property common to a list of items in linq
- remove duplicate items from list in c#
- What is the fastest way to filter a list of strings when making an Intellisense/Autocomplete list?
- LINQ Join to find items NOT IN a list
- Fastest way to select all strings from list starting from
- Find duplicate in a list from a reference list
- C# Linq - Find Duplicate value in list and select it's id
- LINQ: find items in a list that have frequency = 1
- Find Duplicate in list but with criteria
- Count of duplicate items in a C# list
- how to get duplicate items from a list in vb.net
More Query from same tag
- C# LINQ filter the List of tuple with given List
- Why throws exception when using Guid.Parse() method?
- Converting a stored procedure LINQ result list to a DataTable
- Child Cobobox Return Null if DataValue Combobox NotExist in Child table ( LINQ )
- Using GetElementsById to search a website
- Foreach statement takes to long
- Refactoring predicate out of the Lambda expressoin caueses an exception
- LINQ Help for boolean function for a list
- LINQ Group By and select collection
- Referencing null from somewhere I didn't know where
- LINQ Where Ignore Accentuation and Case
- How to convert dynamic value to type value in expression
- How to Groupby in linq
- Visual Studio LINQ for XML distinct list of child tags values
- How to transform grouping with MAX from sql to linq query
- Finding the maximum value in a list
- Using linq with dynamic model in Razor View
- EF Query simplification
- entity framework / linq query construction
- Sort String List Numerically
- Cannot check a string against a char array through Linq method Contains() because the array isn't of type String, conversion to String type fails
- How can I get percentage in LINQ?
- Sort object that contains List and update object using LINQ
- LINQ query sometimes (randomly, for the exact same data) throwing NullReferenceException
- How to add Where Conditions in LINQ Joins
- In Linq, which is more efficient, join or include
- IDictionary extension not actually running while in LInq Query .Where()
- Check if any item is null of System.Collections.IList
- Linq query producing incorrect result
- LINQ to objects vs for each - difference in execution timings