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
- Find Circular Items in a Collection (of non-Transitive Items)
- System.Linq.Dynamic using ?? c# operador
- linq async call to map to one object 2 tables with a foreign key
- .SELECT statement using lambda and Entity Framework
- How can I join conditionally in LINQ queries?
- LINQ Concat nested queries sorting
- how to add XElement in specific location in XML Document
- convert a SQL update statement to a LINQ to Entities
- Why is there an input string exception for a query without where clause?
- how can separate result of object function?
- LINQ join is not using Equals from provided EqualityComparer, uses GetHashCode instead
- nHibernate complex Query
- Adding or to linq query
- Loop through XML with XmlDocument
- List of strings into Bson Array
- Join two tables based on two columns that equal each other
- Linq and IEnumerable lazy query. Efficiency lost?
- Messages answers Grouped By the Parent Original Message
- How do I use LINQ to update a datatable with a SqlDataReader?
- c# list from an array via LINQ + condition
- LINQ - To Get Year from Date which is of Type String
- Using navigation properties instead of LINQ Join in WebApi controller
- C# linq expression not pulling the data correctly
- Convert SUM / CASE WHEN / GROUP BY SQL query into LINQ
- How do I filter a list within a list while maintaining the original form of the object using linq?
- linq query generate defferent results
- Best way to assign a value to a property of all objects in a collection using LINQ
- How can you handle this sub-query with LINQ to SQL?
- Linq2SQL dealing with inserts/deletes on table with unique constraints
- LINQ: get nested arrays based on a groupby?