First, read the Class code below. There you will find a property called- CommonId which is common in Item class and ItemGallery and both has matching int value. Now check the Program class which is the main console program. Here I am adding some data to both classes to make an example. On the bottom of main program class, I am trying to loop through each Item and find its commonId matching with ItemGallery commonId if that commonId matched then in ItemGallery ItemId will be copied from its matching Item Id. The main goal is- Just take the copy from Item class Id to ItemGallery ItemId which has matching commonId. How to do that? I already tried foreach like bellow but this not the correct way.
Main Program Class:
class Program {
static void Main(string[] args) {
List<Item> MyItemList = new List<Item>();
MyItemList.Add(new Item {
CommonId = 502,
Id = 3,
Link = "some string1"
});
MyItemList.Add(new Item {
CommonId = 502,
Id = 4,
Link = "some string2"
});
MyItemList.Add(new Item {
CommonId = 502,
Id = 5,
Link = "some string3"
});
MyItemList.Add(new Item {
CommonId = 506,
Id = 6,
Link = "some string4"
});
List<ItemGallery> MyitemGalleries = new List<ItemGallery>();
MyitemGalleries.Add(new ItemGallery {
CommonId = 502,
Link = "",
});
MyitemGalleries.Add(new ItemGallery {
CommonId = 502,
Link = "",
});
MyitemGalleries.Add(new ItemGallery {
CommonId = 502,
Link = "",
});
foreach (var _MyItemList in MyItemList) {
MyitemGalleries.FirstOrDefault().ItemId = _MyItemList.Where(x => x.CommonId == MyitemGalleries.CommonId).FirstOrDefault().Id;
}
Console.ReadKey();
}
}
Class:
class Item {
public int Id { get; set; }//this id need to set to ItemGallery ItemId matching their CommonId
public int CommonId { get; set; }
public string Link { get; set; }
}
class ItemGallery {
public int ItemId { get; set; }
public int CommonId { get; set; }
public string Link { get; set; }
}
If I understand you and disregarding any other problems, there are few ways to do this. However, a simple foreach and FirstOrDefault should do
foreach (var gallery in MyitemGalleries)
{
var item = _MyItemList.FirstOrDefault(x => x.CommonId == gallery.CommonId);
// note if there are none we choose not to do anything, or grab the first
if(item == null)
continue;
gallery.ItemId = item.Id;
}
Related
I have a class that contains data from another class:
class SecondClass
{
public FirstClass element { get; set; }
public string note { get; set; }
}
Then I create a list of class elements and display it in the datagridview.
firstarray.Add(new FirstClass() { id = 1, name = "name", password = "text" });
foreach (var item in firstarray)
{
if (item.id == 1)
{
secondarray.Add(new SecondClass() { element = item, note = "text" });
}
}
foreach (var item in secondarray)
{
Console.WriteLine(item.element.id);
}
dataGridView1.DataSource = secondarray;
And I get the wrong output of the items. How do I fix this?
I have a set of data that have duplication because of joining to another table. I need to remove the duplicate and add to another List and each of that element include a list of some element.
As example :
I need to insert this data to the list: List<ExistingQuestionDTO> existingQuestions = new List<ExistingQuestionDTO>();
public class ExistingQuestionDTO
{
public int Id { get; set; }
public int QuestionId { get; set; }
public string QuestionTitle { get; set; }
public string SurveyTitle { get; set; }
public int SurveyId { get; set; }
public string OptionType { get; set; }
public IEnumerable<Tag> Tags { get; set; }
}
I took this data to below List:IEnumerable<ExistingQuestionSpResult> existingQuestionSpResults
and try to make an list using below algorithm. But it wont give an expected result.
private IEnumerable<ExistingQuestionDTO> MakeExistingQuestionSearchableDTO(
IEnumerable<ExistingQuestionSpResult> existingQuestionSpResults)
{
int previousQuestionId = 0;
List<Tag> exitingTags = new List<Tag>();
List<Tag> newTags = new List<Tag>();
List<ExistingQuestionDTO> existingQuestions = new List<ExistingQuestionDTO>();
ExistingQuestionDTO previousExistingQuestionDTO = new ExistingQuestionDTO();
foreach (var questionSpResult in existingQuestionSpResults)
{
if (questionSpResult.QuestionId == previousQuestionId ||
previousQuestionId == 0)
{
//Adding new tag if questionId exist for existing tag
if (!(newTags.Count == 0))
{
exitingTags.AddRange(newTags);
//Clear newTags array here...
newTags.Clear();
}
//Add Tags for same array.
if (!(questionSpResult.ColumnName == "NULL"))
{
Tag tag = new Tag
{
TagId = (Guid)questionSpResult.TagId,
TagName = questionSpResult.ColumnName
};
exitingTags.Add(tag);
}
}
else
{
//Add Tags for new array with Other Items too...
exitingTags.Clear();
newTags.Clear();
if (!(questionSpResult.ColumnName == "NULL"))
{
Tag tag = new Tag
{
TagId = (Guid)questionSpResult.TagId,
TagName = questionSpResult.ColumnName
};
newTags.Add(tag);
}
}
ExistingQuestionDTO existingQuestionDTO = new ExistingQuestionDTO
{
Id = questionSpResult.Id,
QuestionId = questionSpResult.QuestionId,
QuestionTitle = questionSpResult.QuestionTitle,
SurveyId = questionSpResult.SurveyId,
SurveyTitle = questionSpResult.SurveyTitle,
OptionType = questionSpResult.OptionType,
Tags = exitingTags.Count != 0 ? exitingTags : newTags
};
if (questionSpResult.QuestionId == previousQuestionId)
{
//Update Tag in relevant node...
//existingQuestions.RemoveAt((int)questionSpResult.QuestionId - 1);
//existingQuestions.Remove(previousExistingQuestionDTO);
//existingQuestions.Add(existingQuestionDTO);
//existingQuestions.Insert(((int)questionSpResult.QuestionId - 1),
// existingQuestionDTO);
var foundQuestion = existingQuestions.Find(a =>
a.QuestionId == questionSpResult.QuestionId);
foundQuestion.Tags = exitingTags;
existingQuestions[(int)questionSpResult.QuestionId - 1] = foundQuestion;
}
else
{
existingQuestions.Add(existingQuestionDTO);
}
previousQuestionId = questionSpResult.QuestionId;
previousExistingQuestionDTO = existingQuestionDTO;
}
IEnumerable<ExistingQuestionDTO> exitingQuestionList = existingQuestions;
return exitingQuestionList;
}
Can somebody show me what went wrong here ?
QuestionId 3 should have Tags.count => 2. But for here it gives 17. I am so confused.
Since redundancy reason is not mentioned properly and row-wise its completely unique except for questionid 3 where the status has both critical and important. So, first, you have to add a filter for the same and see if you are getting completely unique results or not.
I have a controller method that looks like this
//cycles through sites in order to populate variables
foreach (Site s in sites)
{
foreach (OffSiteItemDetails d in s.ItemDetails)
{
if (d.itemID != null)
{
osiItemCost[s.ID] = d.qty * db.Items.Where(x => x.ID == d.itemID).FirstOrDefault().cost(1, false, false);
osiLoItemCost[s.ID] += d.qty * db.Items.Where(x => x.ID == d.itemID).FirstOrDefault().cost(1, false, true);
osiItemLastCost[s.ID] += db.Items.Where(x => x.ID == d.itemID).FirstOrDefault().cost(d.qty, true, false);
}
}
}
o it generates a value for each variable for example osiItemCost[s.ID] could equal 0 for one site ID but it could equal 70 for another Site
So I am trying to create a table for each site ID. Currently if I leave it like
model.OffReportColumns = new List()
It will just keep getting overwritten by the next site Id in the list. So I am trying to assign the list to the sites ID.
foreach (Site s in sites)
{
foreach (OffSiteItemDetails d in s.ItemDetails)
{
model.OffReportColumns[s.ID] = new List<string>()
{
s.Name,
"",
"",
"Average Cost",
"",
"",
"Average Cost (With labour)"
};
Here is my Model class
public class SummaryReportModel
{
public string Title { get; set; }
public string ReportTitle { get; set; }
public string OffReportTitle { get; set; }
public List<string> ValuationColumns { get; set; }
public List<string> OffReportColumns { get; set; }
public List<List<string>> ValuationRows { get; set; }
public List<List<string>> OffReportRows { get; set; }
public List<List<string>> Total { get; set; }
public List<List<string>> OffReporTotal { get; set; }
public List<List<string>> Tital { get; set; }
public List<List<string>> SecondTital { get; set; }
public List<List<string>> osiGrandTotal { get; set; }
}
Where s.ID represents a "site ID"
Currently I receive the errors
Cannot implicitly convert type
'systems.collections.generic.List' to 'string'
However, it works when I remove the [s.ID] so that it looks like this
model.OffReportColumns = new List<string>()
Why is the s.ID causing an issue?
When you use model.OffReportColumns[s.ID] you are referencing the individual string with an index of s.ID. When you use model.OffReportColumns you are referencing the entire list.
You cannot set model.OffReportColumns[s.ID] equal to new List<string>() because a List<string> is not a string
Is not really clear what you are trying to do here. It seems that OffReportColumns is a list of strings, and you are trying to add a list a string to a certain index of it.
If you do this
model.OffReportColumns.AddRange(new List<String>(){
s.Name,
"string test",
"etc."
})
You will add all items of your new list of strings to the end of OffReportColumns.
I have two classes: Group and Item.
public class Group
{
public string Name{ get; set; }
public List<Item> ItemList { get; set; }
}
And then Item
public class Item
{
public int ID{ get; set; }
public string Name{ get; set; }
public string Description{ get; set; }
public Group ItemGroup {get;set;}
}
Each group show have a set of items.
The following code is meant to get the list of items of a particular group, and it works when the ItemGroup in the Items class is set to type string, but not as a type Group.
public IEnumerable<Item> GetItemByGroup(string group)
{
return repository.GetAllItems().Where(
p => string.Equals(p.ItemGroup, group, StringComparison.OrdinalIgnoreCase));
}
How to change the code to get the list of items in a group by its Name property which is set in the Group class.
And how do I set a list/collection of Items in the Group class
I think this should work. Give it a hit
public IEnumerable<Item> GetItemByGroup(string group)
{
return repository.GetAllItems().Where(p =>p.ItemGroup.Name.Equals(group));
}
Update
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<Item> list = new List<Item>();
Item i = new Item()
{
ID = 1,
Name = "Amit",
Description = "Test",
ItemGroup = new Group() { Name = "A" }
};
list.Add(i);
i = new Item()
{
ID = 2,
Name = "Amit1",
Description = "Test1",
ItemGroup = new Group() { Name = "A1" }
};
list.Add(i);
i = new Item()
{
ID = 3,
Name = "Amit11",
Description = "Test11",
ItemGroup = new Group() { Name = "A11" }
};
list.Add(i);
i = new Item()
{
ID = 4,
Name = "Amit111",
Description = "Test111",
ItemGroup = new Group() { Name = "A111" }
};
list.Add(i);
i = new Item()
{
ID = 9,
Name = "Amit4a",
Description = "Test4a",
ItemGroup = new Group() { Name = "A111" }
};
list.Add(i);
i = new Item()
{
ID = 5,
Name = "Amit5",
Description = "Test5",
ItemGroup = new Group() { Name = "A111" }
};
list.Add(i);
i = new Item()
{
ID = 6,
Name = "Amit6",
Description = "Test6",
ItemGroup = new Group() { Name = "A111" }
};
list.Add(i);
var list1 = list.Where(p => p.ItemGroup.Name.Equals("A111"));
// Console.Write(list1.Count());
foreach (var item in list1)
{
Console.WriteLine(string.Format("ID: {0} Name: {1} Description: {2} Group: {3}",item.ID,item.Name,item.Description,item.ItemGroup.Name));
}
Console.Read();
}
}
public class Group
{
public string Name { get; set; }
}
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Group ItemGroup { get; set; }
}
}
What I've got are two classes which each contain Lists of Classes with propperties of different types. The first list is an updated version of the second and i need to find all differences (deleted/added classes in lists and updated classes).
public class ClassOfKb
{
public List<Data> KbData {get;set;}
public List<Info> KbInfo {get;set;}
}
class Data
{
public Guid ID {get;set}
public byte[] file {get;set}
public string name {get;set}
}
class Info
{
public Guid ID {get;set}
public string text {get;set}
public DateTime date {get;set}
}
ClassOfKb KbA = new ClassOfKb();
ClassOfKb KbB = new ClassOfKb();
first KbA and KbB will be filled from the same DataSet, then i delete, add and modify some of KbA Child-Classes.
now i need to compare KbA with KbB to find out where the differences are. i need the ID of deleted or added classes in KbA and the exact changes of modified Child-Classes properties. How would i do this? Preffered with Linq.
I suggest that create two comparers one for Data and one for Info
class DataComparer : IEqualityComparer<Data>
{
public bool Equals(Data x, Data y)
{
//logic to compare x to y and return true when they are equal
}
public int GetHashCode(Data d)
{
//logic to return a hash code
}
}
class InfoComparer : IEqualityComparer<Info>
{
public bool Equals(Info x, Info y)
{
//logic to compare x to y and return true when they are equal
}
public int GetHashCode(Info i)
{
//logic to return a hash code
}
}
The you can use Intersect and Except LINQ methods
IEnumerable<Data> DataInAandNotInB = KbA.KbData.Except(KbB.KbData,new DataComparer());
IEnumerable<Info> InfoInAandInB = KbA.KbInfo.Intersect(KbB.KbInfo,new InfoComparer ());
For simplicity, I skipped comparison of the byte array and DateTime data membes, only left the IDs and the string data members, but to add them you will need some small modification.
The test is very-very basic, but shows all three of the changes options:
static void Main(string[] args)
{
ClassOfKb KbA = new ClassOfKb();
ClassOfKb KbB = new ClassOfKb();
// Test data --------
Data data1 = new Data() { ID = Guid.NewGuid(), name = "111" };
Data data2 = new Data() { ID = Guid.NewGuid(), name = "222" };
Data data2_changed = new Data() { ID = data2.ID, name = "222_changed" };
Data data3 = new Data() { ID = Guid.NewGuid(), name = "333" };
Info info1 = new Info() { ID = Guid.NewGuid(), text = "aaa" };
Info info2 = new Info() { ID = Guid.NewGuid(), text = "bbb" };
Info info2_changed = new Info() { ID = info2.ID, text = "bbb_changed" };
Info info3 = new Info() { ID = Guid.NewGuid(), text = "ccc" };
KbA.KbData.Add(data1);
KbA.KbData.Add(data2);
KbA.KbInfo.Add(info1);
KbA.KbInfo.Add(info2);
KbB.KbData.Add(data2_changed);
KbB.KbData.Add(data3);
KbB.KbInfo.Add(info2_changed);
KbB.KbInfo.Add(info3);
// end of test data ---------
// here is the solution:
var indexes = Enumerable.Range(0, KbA.KbData.Count);
var deleted = from i in indexes
where !KbB.KbData.Select((n) => n.ID).Contains(KbA.KbData[i].ID)
select new
{
Name = KbA.KbData[i].name,
KbDataID = KbA.KbData[i].ID,
KbInfoID = KbA.KbInfo[i].ID
};
Console.WriteLine("deleted:");
foreach (var val in deleted)
{
Console.WriteLine(val.Name);
}
var added = from i in indexes
where !KbA.KbData.Select((n) => n.ID).Contains(KbB.KbData[i].ID)
select new
{
Name = KbB.KbData[i].name,
KbDataID = KbB.KbData[i].ID,
KbInfoID = KbB.KbInfo[i].ID
};
Console.WriteLine("added:");
foreach (var val in added)
{
Console.WriteLine(val.Name);
}
var changed = from i in indexes
from j in indexes
where KbB.KbData[i].ID == KbA.KbData[j].ID &&
(//KbB.KbData[i].file != KbA.KbData[j].file ||
KbB.KbData[i].name != KbA.KbData[j].name ||
//KbB.KbInfo[i].date != KbA.KbInfo[j].date ||
KbB.KbInfo[i].text != KbA.KbInfo[j].text
)
select new
{
Name = KbA.KbData[j].name,
KbDataID = KbA.KbData[j].ID,
KbInfoID = KbA.KbInfo[j].ID
};
Console.WriteLine("changed:");
foreach (var val in changed)
{
Console.WriteLine(val.Name);
}
Console.ReadLine();
}
}
public class ClassOfKb
{
public List<Data> KbData = new List<Data>();
public List<Info> KbInfo = new List<Info>();
}
public class Data
{
public Guid ID { get; set; }
public byte[] file { get; set; }
public string name { get; set; }
}
public class Info
{
public Guid ID { get; set; }
public string text { get; set; }
public DateTime date { get; set; }
}