Compare Dictionary<string,List<object>> - c#

I am comparing two dictionary(dic1 and dic2) with rule that get values from dic2 where key match but values does not match or key is missing in dic2.
Don’t need to iterate through dic2 for missing/different values in dic1.
Below code is working ok I would like to know is there any better way using .NET 2.0 (NO LINQ) .
if optimization is require which option is better?
Dictionary<string,List<foo>> dic1 = new Dictionary<string,List<foo>>();
Dictionary<string,List<foo>> dic2 = new Dictionary<string,List<foo>>();
dic1.add("1", new foo("a"));
dic1.add("2", new foo("b"));
dic1.add("3", new foo("c"));
dic1.add("3", new foo("c1"));
dic1.add("4", new foo("d"));
dic2.add("1", new foo("a"));
dic2.add("2", new foo("b1"));
dic2.add("3", new foo("c"));
dic2.add("3", new foo("c2"));
//I write code which allow duplicate key in dictionary
Option 1
foreach (KeyValuePair<string, List<foo>> var in dic1)
{
if (dic2.ContainsKey(var.Key))
{
List<foo> tempList = var.Value.FindAll(delegate(foo s)
{
return !dic2[var.Key].Contains(s);
});
result.AddRange(tempList);
}
else
{
result.Add(var.Value);
}
}
Option 2
List<string> list1key = new List<string>(dic1.Keys);
list1key.ForEach(delegate(string key)
{
if (dic2.ContainsKey(key))
{
List<foo> tempList = dic1[key].FindAll(delegate(foos)
{
return !dic2[key].Contains(s);
});
result.AddRange(tempList);
}
else
{
result.AddRange(dic1[key]);
}
});

You can speed things up with either option if you use TryGetValue when accessing dic2, so you only have to do a key lookup once.
Your first option looks simpler and possibly faster, i'd go with that.
Cheers

I would use Option 1. Here's a variation on it using TryGetValue instead of looking up dic2[var.Key] so many times:
foreach (KeyValuePair<string, List<foo>> var in dic1)
{
List<foo> dic2val;
if (dic2.TryGetValue(var.Key, out dic2val))
{
List<foo> tempList = var.Value.FindAll(delegate(foo s)
{
return !dic2val.Contains(s);
});
result.AddRange(tempList);
}
else
{
result.Add(var.Value);
}
}

Related

Adding element to a list in class, which is a part of List<class>, based on condition

Let's have a simple class with 2 fields
public class Sample
{
public int IdOfSample;
public string SampleName;
}
And another using this one
public class ListOfSamples
{
public int IdOfList;
public List<Sample> SampleList;
}
And finally, since we will use a couple of different ListOfSamples, make a list of them:
public static List<ListOfSamples> FinalList = new List<ListOfSamples>();
Now the problem:
I create a new Sample (let's call it NewItem), with some name and Id. I want to check if there's a ListOfSamples in my FinalList that as the same Id as the NewItem I have. Otherwise create new ListOfSamples in the FinalList with the IdOfList = NewItem.IdOfSample.
I think I got the first part which checks if you should add a new list (ie. a ListOfSamples with specified IdOfList does not exist:
Sample NewItem = new Sample()
{
IdOfSample = 12345,
SampleName = "Some name"
};
int index = FinalList.FindIndex(f => f.IdOfList == NewItem.IdOfSample);
if (!FinalList.Any() || index == -1)
{
ListOfSamples NewList = new ListOfSamples()
{
IdOfList = NewItem.IdOfSample,
SampleList = new List<Sample>()
};
NewList.SampleList.Add(NewItem);
FinalList.Add(NewList);
}
Now, I'm trying to construct a statement, that, if the list with specified Id already exists in the FinalList, just add the new item to it, but so far I think my limited experience with LINQ is showing, nothing I try seems to work.
So:
If there exists a ListOfSamples with IdOfList == NewItem.IdOfSample in FinalList, then add NewItem to that ListOfSamples.
How about
if (!FinalList.Any() || index == -1)
...
else
{
FinalList[index].SampleList.Add(NewItem);
}
If you just wanted to check whether the list item existed, a suitable LINQ statement could be:
if (FinalList.Any(l => l.IdOfList == NewItem.IdOfSample))
{
// ...
}
Given you want to work on the item then you could attempt to retrieve it as follows:
var existingList = FinalList.SingleOrDefault(l => l.IdOfList == NewItem.IdOfSample);
if (existingList != null)
{
existingList.Add( ... );
}
Though perhaps it's worth thinking about using a HashSet of lists if you want to guarantee uniqueness...
if i understand it right ...
// search for the list with the given Id
var listOfSamples = finalList.Where(fl => fl.IdOfList == newItem.IdOfSample).FirstOrDefault();
if (listOfSamples == null)
{
// not found
// add new List with the new item in final list
finalList.Add(new ListOfSamples {IdOfList = newItem.IdOfSample, SampleList = new List<Sample>{newItem}} );
}
else
{
// found
// add the new item into the found list
listOfSamples.SampleList.Add(newItem);
}
If you replace ListOfSamples with a Dictionary<int, List<Sample>> then you will gain the ability to do a lookup in O(1) time and guarantee that the ids at the top level are unique. and then you can just add stuff like this.
Dictionary<int, List<Sample>> FinalList = new Dictionary<int, List<Sample>>();
Sample NewItem = new Sample()
{
IdOfSample = 12345,
SampleName = "Some name"
};
List<Sample> list;
if (!FinalList.TryGetValue(NewItem.IdOfSample, out list))
{
list = new List<Sample>();
FinalList.Add(NewItem.IdOfSample, list);
}
list.Add(NewItem);
TryGetValue will see if the dictionary has an entry for the key you pass it and returns true if it does and false if it does not. If it does have an entry for the key it also assigns the value of the entry (in this case your list of samples) to the out parameter. So, we check if it returns false and in that case we create a new list and add it to the dictionary. Then we add the sample to the list that we either got from the dictionary, or just created and put in the dictionary.

Check same elements in two lists

I have a List and a ListItemCollection and want to check if there have the same elements.
First, I fill the ListItemCollection with Text and Value. (After a SQL Select)
ListItemCollection tempListName = new ListItemCollection();
ListItem temp_ListItem;
if (reader.HasRows)
{
while (reader.Read())
{
temp_ListItem = new ListItem(reader[1].ToString(), reader[0].ToString());
tempListName.Add(temp_ListItem);
}
}
and I have the List
List<string> tempList = new List<string>(ProfileArray);
with some values like {"1","4","5","7"}
now, I want to check, if the tempList have maybe some elements with the same value in tempListName and read the text from the value adn write it in a new list.
Note: Im using asp.net 2.0.
List.FindAll was already available in C# 2.0:
List<string> newList = tempList.FindAll(s => tempListName.FindByText(s) != null);
ListItemCollection.FindByText:
Use the FindByText method to search the collection for a ListItem with
a Text property that equals text specified by the text parameter. This
method performs a case-sensitive and culture-insensitive comparison.
This method does not do partial searches or wildcard searches. If an
item is not found in the collection using this criteria, null is
returned.
Real simple solution that you can customize and optimize as per your needs.
List<string> names = new List<string>(); // This will hold text for matched items found
foreach (ListItem item in tempListName)
{
foreach (string value in tempList)
{
if (value == item.Value)
{
names.Add(item.Text);
}
}
}
So, for a real simple example, consider something like this:
List<string> tempTextList = new List<string>();
while (reader.Read())
{
string val = reader[0].ToString(),
text = reader[1].ToString();
if (tempList.Contains(val)) { tempTextList.Add(text); }
temp_ListItem = new ListItem(text, val);
tempListName.Add(temp_ListItem);
}
Now, just having a listing of the text values doesn't do you much good, so let's improve that a little:
Dictionary<string, string> tempTextList = new Dictionary<string, string>();
while (reader.Read())
{
string val = reader[0].ToString(),
text = reader[1].ToString();
if (tempList.Contains(val)) { tempTextList.Add(val, text); }
temp_ListItem = new ListItem(text, val);
tempListName.Add(temp_ListItem);
}
Now you can actually find the text for a specific value from the dictionary. You might even want to declare that Dictionary<string, string> in a higher scope and use it elsewhere. If you were to declare it at a higher scope, you'd just change one line, this:
Dictionary<string, string> tempTextList = new Dictionary<string, string>();
to this:
tempTextList = new Dictionary<string, string>();
var resultList = new List<string>();
foreach (string listItem in tempList)
foreach (ListItem listNameItem in tempListName)
if (listNameItem.Value.Equals(listItem))
resultList.Add(listNameItem.Text);

Compare List<string> and enable the required control

I am having two list<string> as follows
listA is having the following values 10,20,30,40 and
listB is having the following values 10,20,30
If listB contains listA elements i would like to enable particular controls if not i would like to disable the Controls
I tried of using two loops as follows
for(int ilist1=0;ilist1<listA.count;ilist1++)
{
for(int ilist2=0;ilist2<listB.count;ilist2++)
{
if(listA[ilist1]==listB[ilist2])
{
//Enable particular control
}
}
}
But i know this is not an appropriate one to do so can any one tell me the best approach to achieve this
What you want to do is to hash the items in the first list into a set then verify for each item in the second is within the set. Unfortunately the HashSet<> is not available so the closest you can get is the Dictionary<,>.
Do this:
Dictionary<string, string> set = new Dictionary<string, string>();
foreach (string item in listA)
{
set.Add(item, item);
}
foreach (string item in listB)
{
if (!set.ContainsKey(item))
{
//Enable particular control
}
}
It's easy by using the Intersect method:
if (listB.Intersect(listA).Count() > 0)
{
//enable Control
}
else
{
//disable control
}
I think you are looking for something like this
List<string> lista = new List<string>() {"10","40","30" };
List<string> listb = new List<string>() { "10", "20" };
var diff = listb.Except<string>(lista);
diff should give you the ones which didn't match else all would have been matched.
For 2.0
if (listb.TrueForAll(delegate(string s2) { return lista.Contains(s2); }))
MessageBox.Show("All Matched");
else
MessageBox.Show("Not Matched");
In fx 2.0, you can do it like this:
string b = listA.Find(delegate(string a) { return listB.Contains(a); });
if (string.IsNullOrEmpty(b))
{
//disable control
}
else
{
//enable control
}
Control.Enabled = listB.Intersect(listA).Any()
Note that Any() will only check to see if there is at least one item. Count() > 0 will evaluate the entire collection when you only need to check if there is at least one item
Edit: If you are in a .NET 2.0 environment then you can loop through and do this:
foreach (int item in listB)
{
if (listA.Contains(item))
return true;
}
return false;

Lucene.NET and searching on multiple fields with specific values

I've created an index with various bits of data for each document I've added, each document can differ in it field name.
Later on, when I come to search the index I need to query it with exact field/ values - for example:
FieldName1 = X AND FieldName2 = Y AND FieldName3 = Z
What's the best way of constructing the following using Lucene .NET:
What analyser is best to use for this exact match type?
Upon retrieving a match, I only need one specific field to be returned (which I add to each document) - should this be the only one stored?
Later on I'll need to support keyword searching (so a field can have a list of values and I'll need to do a partial match).
The fields and values come from a Dictionary<string, string>. It's not user input, it's constructed from code.
Thanks,
Kieron
Well, I figured it out eventually - here's my take on it (this could be completely wrong, but it works for):
public Guid? Find (Dictionary<string, string> searchTerms)
{
if (searchTerms == null)
throw new ArgumentNullException ("searchTerms");
try
{
var directory = FSDirectory.Open (new DirectoryInfo (IndexRoot));
if (!IndexReader.IndexExists (directory))
return null;
var mainQuery = new BooleanQuery ();
foreach (var pair in searchTerms)
{
var parser = new QueryParser (
Lucene.Net.Util.Version.LUCENE_CURRENT, pair.Key, GetAnalyzer ());
var query = parser.Parse (pair.Value);
mainQuery.Add (query, BooleanClause.Occur.MUST);
}
var searcher = new IndexSearcher (directory, true);
try
{
var results = searcher.Search (mainQuery, (Filter)null, 10);
if (results.totalHits != 1)
return null;
return Guid.Parse (searcher.Doc (results.scoreDocs[0].doc).Get (ContentIdKey));
}
catch
{
throw;
}
finally
{
if (searcher != null)
searcher.Close ();
}
}
catch
{
throw;
}
}

What's the pattern to use for iterating over associated sets of values?

It's pretty common - especially as you try to make your code become more data-driven - to need to iterate over associated collections. For instance, I just finished writing a piece of code that looks like this:
string[] entTypes = {"DOC", "CON", "BAL"};
string[] dateFields = {"DocDate", "ConUserDate", "BalDate"};
Debug.Assert(entTypes.Length == dateFields.Length);
for (int i=0; i<entTypes.Length; i++)
{
string entType = entTypes[i];
string dateField = dateFields[i];
// do stuff with the associated entType and dateField
}
In Python, I'd write something like:
items = [("DOC", "DocDate"), ("CON", "ConUserDate"), ("BAL", "BalDate")]
for (entType, dateField) in items:
# do stuff with the associated entType and dateField
I don't need to declare parallel arrays, I don't need to assert that my arrays are the same length, I don't need to use an index to get the items out.
I feel like there's a way of doing this in C# using LINQ, but I can't figure out what it might be. Is there some easy method of iterating across multiple associated collections?
Edit:
This is a little better, I think - at least, in the case where I have the luxury of zipping the collections manually at declaration, and where all the collections contain objects of the same type:
List<string[]> items = new List<string[]>
{
new [] {"DOC", "DocDate"},
new [] {"CON", "ConUserDate"},
new [] {"SCH", "SchDate"}
};
foreach (string[] item in items)
{
Debug.Assert(item.Length == 2);
string entType = item[0];
string dateField = item[1];
// do stuff with the associated entType and dateField
}
In .NET 4.0 they're adding a "Zip" extension method to IEnumerable, so your code could look something like:
foreach (var item in entTypes.Zip(dateFields,
(entType, dateField) => new { entType, dateField }))
{
// do stuff with item.entType and item.dateField
}
For now I think the easiest thing to do is leave it as a for loop. There are tricks whereby you can reference the "other" array (by using the overload of Select() that provides an index, for example) but none of them are as clean as a simple for iterator.
Here's a blog post about Zip as well as a way to implement it yourself. Should get you going in the meantime.
Create a struct?
struct Item
{
string entityType;
string dateField;
}
Pretty much the same as your Pythonic solution, except type-safe.
This is realy a variation on the other themes, but this would do the trick also...
var items = new[]
{
new { entType = "DOC", dataField = "DocDate" },
new { entType = "CON", dataField = "ConUserData" },
new { entType = "BAL", dataField = "BalDate" }
};
foreach (var item in items)
{
// do stuff with your items
Console.WriteLine("entType: {0}, dataField {1}", item.entType, item.dataField);
}
You can use the pair and a generic List.
List<Pair> list = new List<Pair>();
list.Add(new Pair("DOC", "DocDate"));
list.Add(new Pair("CON", "ConUserDate"));
list.Add(new Pair("BAL", "BalDate"));
foreach (var item in list)
{
string entType = item.First as string;
string dateField = item.Second as string;
// DO STUFF
}
Pair is part of the Web.UI, but you can easily create your own custom class or struct.
If you just want to declare the lists inline, you can do that in one step:
var entities = new Dictionary<string, string>() {
{ "DOC", "DocDate" },
{ "CON", "ConUserDate" },
{ "BAL", "BalDate" },
};
foreach (var kvp in entities) {
// do stuff with kvp.Key and kvp.Value
}
If they're coming from other things, we have a bunch of extension methods to build dictionaries from various data structures.

Categories

Resources