score:1
You can get rid of the inner loop using System.Linq. Also simplify code by using foreach instead of for for main loop:
ConcurrentDictionary<string, string> compareDictionary = new ConcurrentDictionary<string, string>();
foreach (var element in list1)
{
var item1Name= element.Name.ToString();
var item1Id= element.ID.ToString();
// If this element has already one correspondence, TryAdd will fail anyway
if(compareDictionary.ContainsKey(item1Id)) continue;
var found = list2.FirstOrDefault(item => item1Name.Contains(item.item2Name.ToLower()));
if(found != null)
{
compareDictionary.TryAdd(item1Id, item.item2Id);
}
}
Depending on your elements naming, you also could need to make item1Name lower case. Your code will in fact find this correspondence:
Parentwithlittlechild --> LittleChild
but not this:
ParentWithLittleChild --> LittleChild
because "LittleChild" would be lower cased, and String.Contains works case sensitively by default.
You could also use IndexOf
method with StringComparison.OrdinalIgnoreCase
, like this:
var found = list2.FirstOrDefault(item => item1Name.IndexOf(item.item2Name, StringComparison.OrdinalIgnoreCase) >= 0);
Final consideration: element.Name
is probably already of type string, unless your Item1.Name
property is some funny type. If so, element.Name.ToString()
is convertible in just element.Name
.
score:1
Couple of code snippets to find the matches and add the ids
of the two objects in a ConcurrentDictionary<string, string>
.
So we have:
var dict = new ConcurrentDictionary<string, string>();
First
list1.ForEach(x =>
{
list2.Where(y => y.Item2Name.IndexOf(x.Name, StringComparison.CurrentCultureIgnoreCase) >= 0)
.ToList().ForEach(y => dict.TryAdd(x.ID, y.Item2Id));
});
Second
(from x in list1
from y in list2
where x.Name.IndexOf(y.Item2Name, StringComparison.CurrentCultureIgnoreCase) >= 0
select (x, y)).ToList().ForEach(item => dict.TryAdd(item.x.ID, item.y.Item2Id));
Side Note
If both
Item1.Name
andItem2.Item2Name
properties are ofstring
type, then no need to useToString()
function like invar item1Name= list1[i].Name.ToString();
line.If both
Item1.ID
andItem2.Item2Id
properties are ofint
type, then the proper type of bothKey
andValue
pairs of the dictionary is theint
type. So:
var dict = new ConcurrentDictionary<int, int>();
Source: stackoverflow.com
Related Query
- Compare items in two lists and replace foreach loop with LINQ
- Mapping two lists of points and replace with linq
- Easiest way of comparing two lists in C# with LINQ and adding missing items to Entity Class
- C# LINQ code for two list compare and replace
- Join two lists and select nested items with linq
- Compare two lists with linq and lambda where one is string and other long
- compare two list and return not matching items using linq
- Get different and common items in two arrays with LINQ
- Replace foreach loop with linq
- Left join on two Lists and maintain one property from the right with Linq
- LINQ compare two lists and remove
- Simplifying a foreach loop with LINQ (selecting two objects in each iteration)
- how can compare items of two lists with linq?
- Using Linq and C#, trying to get two lists from a list of master items grouped by two inner lists
- Replace two foreach loops with linq
- Compare id's of objects in two lists and get the list of objects that includes objects with ids occurring in both of them
- Using Linq and C#, is it possible to join two lists but with interleaving at each item?
- Compare two object lists with LINQ on specific property
- Compare lists and get values with Linq
- Compare two list in C# and reject or select the child list based on conditions using LINQ or foreach
- How to compare two lists with multiple objects and set values?
- How do I compare two lists where one list starts with the other, and only return the "overhang" elements?
- Linq to format a list of items to replace foreach loop
- How to merge two lists while adding metadata indicating value source with LINQ statement?
- Comparing two lists and return not matching items results with error
- LINQ - select from db and compare two lists
- Use LINQ to compare two lists, and produce a third one with results from one OR the other
- How to match two Lists with only items that are different in Linq
- Nested foreach conversion to LINQ with a condition on two lists
- Compare two lists and remove items that are not found in list2
More Query from same tag
- How to solve this Error in Linq : Operator '!=' cannot be applied to operands of type 'int' and 'System.Linq.IQueryable<int>'
- LINQ: Add to list for each item
- EF MVC connection string and associations
- LINQ Help, data type of returned set
- Removing elements in list that appear in dict
- How do I use Entity Framework to find a record in Cosmos with case insensitive conditions
- Linq Outer Joins - don't want DefaultIfEmpty, rather want NullIfEmpty
- How to specify which columns can be returned from linq to sql query
- C# Groupby then Sum after Split CSV (no Headers)
- LINQ to Entities DeleteAllOnSubmit throws Unknown Method
- Creating A Filetree from a directory with Json.net LINQ
- Get the Latest date object in List of Tuples objects using Linq C#
- How to perform sql join on Dictionary<string,List<string>>?
- Splitting a list of dates/weeks into a and b weeks with LINQ
- Using linq to calculate rating average in EF Core
- DayOfWeek in LINQ query
- Should I invest time in learning about OR\M or LINQ?
- What might cause a Stack Overflow during linq iteration of Dictionary?
- linq group by contiguous blocks
- How to filter records from a db using linq expressions?
- linq select new and string
- How to update an item in a list keeping the rest of the list intact through Linq
- linq join tables with multiple columns with or condition
- How to combine two linq queries using Union
- Get unique users per hour/day/month
- Query Context for Inserted but yet Uncommitted records
- Is linq different from linq to sql?
- How to search the correct way in .NET enums
- Inserting records on multiple tables in a single method using Entity Framework
- Clever regex and LINQ in C#