I am trying the following:
public class ResultDTO
{
public int Id { get; set; }
public string Text { get; set; }
public int AnswerId { get; set; }
public string AnswerText { get; set; }
}
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO () { Id:1, Text: "abc", AnswerId: "1", AnswerText: "Aab1" },
new ResultDTO () { Id:1, Text: "abc", AnswerId: "2", AnswerText: "Aab2" },
new ResultDTO () { Id:1, Text: "abc", AnswerId: "3", AnswerText: "Aab3" },
new ResultDTO () { Id:1, Text: "def", AnswerId: "4", AnswerText: "Aab4" },
new ResultDTO () { Id:1, Text: "def", AnswerId: "5", AnswerText: "Aab5" },
new ResultDTO () { Id:1, Text: "def", AnswerId: "6", AnswerText: "Aab6" }
}
This gives me many syntax errors in the IDE. Can someone advise what I am doing wrong?
This is not JSon object and array. the property can be assigned using = operator.
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO () { Id=1, Text= "abc", AnswerId= 1, AnswerText= "Aab1" },
....
}
I would like to suggest you to create constructor which is having parameters for properties;
public class ResultDTO
{
public int Id { get; private set; }
public string Text { get; set; }
public int AnswerId { get; set; }
public string AnswerText { get; set; }
public ResultDTO(int id, string _text, int ansId, string ansText)
{
Id=id;
Text = _text;
AnswerId = ansId;
AnswerText = ansText;
}
}
then initialize the list like this.
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO (1,"abc",1,"Aab1"),
new ResultDTO (1,"abc",2,"Aab2"),
new ResultDTO (1,"abc",3,"Aab3"),
....
}
This will give you some advantage when you specify the property readonly. Look at the above class I have declared Id property publicly readable and cannot be set out of the class.
When initializing a class you need to use = instead of :
public class ResultDTO
{
public int Id { get; set; }
public string Text { get; set; }
public int AnswerId { get; set; }
public string AnswerText { get; set; }
}
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO () { Id=1, Text= "abc", AnswerId= 1, AnswerText= "Aab1" },
new ResultDTO () { Id=1, Text= "abc", AnswerId= 2, AnswerText= "Aab2" },
new ResultDTO () { Id=1, Text= "abc", AnswerId= 3, AnswerText= "Aab3" },
new ResultDTO () { Id=1, Text= "def", AnswerId= 4, AnswerText= "Aab4" },
new ResultDTO () { Id=1, Text= "def", AnswerId= 5, AnswerText= "Aab5" },
new ResultDTO () { Id=1, Text= "def", AnswerId= 6, AnswerText= "Aab6" }
}
Related
I have a class:
public class User
{
public Guid ObjectId { get; set; }
public List<Guid> Groups { get; set; }
}
public class Group
{
public List<User> Users { get; set; }
}
Example:
Users:
[
{
"ObjectId": "1",
"Groups": ["G1"]
},
{
"ObjectId": "2",
"Groups": ["G2"]
},
{
"ObjectId": "3",
"Groups": ["G3"]
},
{
"ObjectId": "1",
"Groups": ["G4"]
}
]
Note that ObjectId "1" is present 2 times (One with G1, One with G4)
On running
var source = Group.SelectMany(x => x.Users).ToList();
I see the output as:
[
{
"ObjectId": "1",
"Groups": ["G1"]
},
{
"ObjectId": "2",
"Groups": ["G2"]
},
{
"ObjectId": "3",
"Groups": ["G3"]
}
]
How do I get the output as:
[
{
"ObjectId": "1",
"Groups": ["G1"]
},
{
"ObjectId": "2",
"Groups": ["G2"]
},
{
"ObjectId": "3",
"Groups": ["G3"]
},
{
"ObjectId": "1",
"Groups": ["G4"]
}
]
If the input is:
Users:
[
{
"ObjectId": "1",
"Groups": ["G1"]
},
{
"ObjectId": "2",
"Groups": ["G2"]
},
{
"ObjectId": "3",
"Groups": ["G3"]
},
{
"ObjectId": "1",
"Groups": ["G1"]
}
]
The output should be:
[
{
"ObjectId": "1",
"Groups": ["G1"]
},
{
"ObjectId": "2",
"Groups": ["G2"]
},
{
"ObjectId": "3",
"Groups": ["G3"]
}
]
UPDATE:
Apologize as my question was not clear:
Classes:
public class GroupMembership
{
public List<AzureADUser> SourceMembers { get; set; }
}
public class AzureADUser
{
public Guid ObjectId { get; set; }
public List<Guid> SourceGroups { get; set; }
}
var users1 = new List<AzureADUser> {
new () { ObjectId = new Guid("Guid1"), SourceGroups = new List<Guid> {new Guid("GuidG1")}},
new () { ObjectId = new Guid("Guid2"), SourceGroups = new List<Guid> {new Guid("GuidG2")}},
new () { ObjectId = new Guid("Guid3"), SourceGroups = new List<Guid> {new Guid("GuidG3")}},
new () { ObjectId = new Guid("Guid1"), SourceGroups = new List<Guid> {new Guid("GuidG4")}} //include this
};
var users2 = new List<AzureADUser> {
new () { ObjectId = new Guid("Guid1"), SourceGroups = new List<Guid> {<GuidG1>}} // remove this as this is a duplicate
};
var groupMembership1 = new GroupMembership
{
SourceMembers = users1;
};
var groupMembership2 = new GroupMembership
{
SourceMembers = users2;
};
var groupsMemberships = new List<GroupMembership>();
groupsMemberships.Add(groupMembership1);
groupsMemberships.Add(groupMembership2);
/* output:
ObjectId: new Guid("Guid1"), SourceGroups: new Guid("Guid1")
ObjectId: new Guid("Guid2"), SourceGroups: new Guid("Guid2")
ObjectId: new Guid("Guid3"), SourceGroups: new Guid("Guid3")
ObjectId: new Guid("Guid1"), SourceGroups: new Guid("GuidG4")
*/
SelectMany isn't the problematique API here, it just collects the existing sub-collections of Users into one. It's doesn't remove any and doesn't look at the data at all.
If your goal is to remove duplicates from your list, you could use LINQ's Distinct method on the result of SelectMany - and provide the appropriate IEqualityComparer that checks the User data for equaility. The comparison should return true if all values, ObjectID and all elements in Group, are equal.
Your code is somewhat confusing: Your JSON deals with ints and strings, but the class defs uses GUIDs. I'll use the JSON definition for the following example:
public static void Main()
{
var users = new List<User> {
new () { ObjectId = 1, Groups = new () {"G1"}},
new () { ObjectId = 2, Groups = new () {"G2"}},
new () { ObjectId = 3, Groups = new () {"G3"}},
new () { ObjectId = 1, Groups = new () {"G4"}}, // should remain
new () { ObjectId = 1, Groups = new () {"G1"}}, // should be removed equal to 1st
};
var distinct = users.Distinct(new UserComp());
foreach (var usr in distinct)
Console.WriteLine(usr);
/* output:
ID: 1, Groups: G1
ID: 2, Groups: G2
ID: 3, Groups: G3
ID: 1, Groups: G4
*/
}
public class UserComp : IEqualityComparer<User> {
public bool Equals (User usr1, User usr2)
{
if (usr1 is null) return usr2 is null;
if (usr2 is null) return false;
return usr1.ObjectId == usr2.ObjectId && ((usr1.Groups is {} g1 && usr2.Groups is {} g2 && g1.SequenceEqual(g2)) || (usr1.Groups is null && usr2.Groups is null));
}
// hash is kind of weak ignoring the group data, but suitable for the demo
public int GetHashCode (User usr) => usr?.ObjectId ?? 0;
}
public class User
{
public int ObjectId { get; set; }
public List<string> Groups { get; set; }
public override string ToString () => $"ID: {ObjectId}, Groups: {(Groups == null ? "-" : string.Join(", " ,Groups))}";
}
Note that you don't need an explicit equaility comparer class if you put the same logic into the override of User.Equals.
I have a class with collection class inside
public class SearchResult {
public int Id { get; set; }
public int Total { get; set; }
public IEnumerable<Book> Books { get; set; }
}
public class Book {
public int BookId { get; set; }
public string BookName { get; set; }
public string Publisher { get; set; }
public string ISBNCode { get; set; }
public IList<catagory> Catagories { get; set; }
}
I have a question , if I create the other object , with same structure of SearchResult and I want to copy SearchResult to SearchResultClone, which inside Books only copy BookId and BookName remain is empty.
Just like below
{
"Id": 0,
"Total": 3,
"Books": [
{
"BookId": 1,
"BookName": "Book A",
"Publisher": "",
"ISBNCode": "",
"Catagories": []
},
{
"BookId": 2,
"BookName": "Book B",
"Publisher": "",
"ISBNCode": "",
"Catagories": []
},
{
"BookId": 3,
"BookName": "Book C",
"Publisher": "",
"ISBNCode": "",
"Catagories": []
}
]
}
Event the original result have value of Publisher, ISBNCode ..etc
How to do it in LINQ ?
My second question is , if I want to make a fluent assertions as above object
var result = await sut.search(query);
result.Should().BeEquivalentTo ({the SearchResultClone })
How to write this fluent assertion ?
You need to create new instances of the classes based on the old instances:
var ans = result.Select(sr => new SearchResult {
Id = sr.Id,
Total = sr.Total,
Books = sr.Books.Select(b => new Book { BookId = b.BookId, BookName = b.BookName }).ToList()
}).ToList();
result.Should().BeEquivalentTo ({the SearchResultClone })
How to write this fluent assertion ?
If your expectation (the object you pass into BeEquivalentTo) is of the type SearchResult, then FA will try to compare the empty values of ISBN to the same property on the sut. You can solve that by doing something like:
sut.Should().BeEquivalentTo(new
{
Id = "some value",
Total = 123,
Books = new[]
{
new
{
BookId = 123,
BookName = "some book"
}
}
});
I want to create JSON object with following format:-
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
"message": "error-message"
}
],
"success": [
{
"message": "success-message"
}
]
}
I have tried the following, but it doesn't help me.
dynamic record = new { result = new {name="", address=""},
error = new {message=""},
success = new {message=""} };
Update 1:-
Here is my code:-
List addressList = new List();
// Loop over items within the container and URI.
foreach (var item in items)
{
dynamic record = new { result = new object[] {
new {name = item.name, address = item.address} } };
addressList.Add(record);
}
Result:-
[ {
"result": [
{
"name": "John",
"address": "US"
}
]
},
{
"result": [
{
"name": "Jack",
"address": "CA"
}
]
}
]
Expected json result:-
[{
"result": [{
"name": "John",
"address": "US"
}]
},
{
"result": [{
"name": "Jack",
"address": "CA"
}],
"error": [{
"message": "error-message"
}],
"success": [{
"message": "success-message"
}]
}
]
How do I update my code to get above expected json result?
You...create arrays. You're not doing that. You're creating individual objects.
Something along the lines of:
dynamic record = new {
result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
},
error = new object[] /*...*/,
success = new object[] /*...*/
};
If you want exactly JSON, then newtonsoft.Json makes it easier:
Json json = new Json();
json.result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
};
// json.error = ... and so on
string output = JsonConvert.SerializeObject(product);
The output you will have is:
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
...
}
]
}
To deserialize it back, use:
Json deserializedJson = JsonConvert.DeserializeObject<Json>(output);
you are not creating an array
if you want to create JSON arrays from c# you have to use the following POCO
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
and then use Json.net
var json = JsonConvert.SerializeObject( "your instance of the root Object")
//You need to make this class structure first
public class Response
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
// And then you can use it like this
var response = new Response()
{
result = new List<Result>
{
new Result() {name = "Jhon", address = "US"},
new Result() {name = "Jhon", address = "US"},
},
error = new List<Error>()
{
new Error() {message = "error-message 1"},
new Error() {message = "error-message 2"}
},
success = new List<Success>()
{
new Success(){message = "success-message 1"},
new Success(){message = "success-message 2"},
}
};
The Model Class
public class MegaMenu
{
public int department_id { get; set; }
public string department_name { get; set; }
public List<SectionListData> sectionListData { get; set; }
}
public class SectionListData
{
public int section_id { get; set; }
public string section_name { get; set; }
public List<ItemHeadList> itemHeadList { get; set; }
}
public class ItemHeadList
{
public int item_head_id { get; set; }
public string item_name { get; set; }
}
public class WrapperMegaMenu
{
public List<MegaMenu> megaMenuList { get; set; }
public string error { get; set; }
}
The Services
dept_result is the array of all department,section_result is the array of all section,Item_result is the array of all items
List<MegaMenu> listmenu = new List<MegaMenu>();
foreach (var each_dept in dept_result)
{
MegaMenu megaMenu = new MegaMenu();
megaMenu.department_id = each_dept.shopdepartment_id;
megaMenu.department_name = each_dept.name_en;
var temSectionList = section_result
.Where(item => item.shopdepartment_id == each_dept.shopdepartment_id).ToList().Select(sectionData => new SectionListData
{
section_id = sectionData.shopsection_id,
section_name = sectionData.name_en,
itemHeadList = Item_result.Where(itemHead => itemHead.shopsection_id == sectionData.shopsection_id).ToList().Select(itemHeadData => new ItemHeadList {
item_head_id = itemHeadData.item_head_id,
item_name = itemHeadData.name_en
}).ToList()
}).ToList();
megaMenu.sectionListData = temSectionList;
listmenu.Add(megaMenu);
}
//wrapperDept.departmentList = dept_result.ToList();
wrapper.megaMenuList = listmenu.ToList();
Result
{
"megaMenuList": [
{
"department_id": 71,
"department_name": "Baby's Hygiene",
"sectionListData": [
{
"section_id": 56,
"section_name": "Diapers",
"itemHeadList": []
},
{
"section_id": 57,
"section_name": "Wipes",
"itemHeadList": [
{
"item_head_id": 142,
"item_name": "Telivision"
}
]
}
]
}
]
}
I have a class and want to add some data on construction so i can used it without using database like :
public partial class ActionTypeList
{
public ActionTypeList()
{
new ActionTypeList { Id= "2", FName= "hanumanji" };
new ActionTypeList { Id= "4", FName= "temples" };
new ActionTypeList { Id= "38", FName= "books" };
new ActionTypeList { Id= "28", FName= "stories" };
}
public string Id{ get; set; }
public string FName{ get; set; }
}
I just given an example, how to do it I don't know.
If you need some data to work with then you will want to create separate instances outside the class not in it, that is a bad practice. If you truly feel that you must have data in this class then add a static method to get some your default stuff.
public partial class ActionType
{
public string Id { get; set; }
public string FName { get; set; }
public static IEnumerable<ActionType> GetDefaultActionTypes() {
return new List<ActionType> {
new ActionType { Id = "2", FName = "hanumanji" },
new ActionType { Id = "4", FName = "temples" },
new ActionType { Id = "28", FName = "books" },
new ActionType { Id = "38", FName = "stories" },
};
}
}
You can then use the static method like this
var myDefaultActionTypes = ActionType.GetDefaultActionTypes();
Create a new class ActionType and store your items in the ActionTypeList:
public class ActionType {
public ActionType() {
}
public string Id { get; set; }
public string FName { get; set; }
}
public class ActionTypeList : List<ActionType> {
public ActionTypeList() {
Add(new ActionType() { Id = "2", FName = "hanumanji" });
Add(new ActionType { Id = "4", FName = "temples" });
Add(new ActionType { Id = "38", FName = "books" });
Add(new ActionType { Id = "28", FName = "stories" });
}
}
You can define a static method inside of your class
public static List<ActionTypeList> GetActionTypes()
{
return new List<ActionTypeList>
{
new ActionTypeList { Id= "2", FName= "hanumanji" };
new ActionTypeList { Id= "4", FName= "temples" };
new ActionTypeList { Id= "38", FName= "books" };
new ActionTypeList { Id= "28", FName= "stories" };
}
}
And whenever you want to get your sample list you can call this method.
var list = ActionTypeList.GetActionTypes();
I have some problem here. Here it is:
I have this class
public class NewsFeedResources
{
public string Name { get; set; }
public string Id { get; set; }
public string Message { get; set; }
public static ObservableCollection<NewsFeedResources> _newsfeed = new ObservableCollection<NewsFeedResources>
{
new NewsFeedResources { Name = "Joe", Id = "1", Message="Foo" },
new NewsFeedResources { Name = "Wandy", Id = "2", Message="Bar" },
new NewsFeedResources { Name = "Yuliana", Id = "3", Message="Baz" },
new NewsFeedResources { Name = "Hardi", Id = "4", Message="Baz" },
};
public static ObservableCollection<NewsFeedResources> newsFeedResources
{ get { return _newsfeed; }
}
}
If I have another data such as
Name=John, Id=5, Message="Stack overflow"
Name=Jane, Id=6, Message="Hello world"
How can I add the data into the class, but not from the constructor? Thanks for the help
ObservableCollection exposes the Collection<T>.Add Method:
Adds an object to the end of the Collection.
So you'd have:
_newsfeed.Add(new NewsFeedResources {Name = "John",
Id = 5,
Message = "Stack overflow"});
_newsfeed.Add(new NewsFeedResources {Name = "Jane",
Id = 6,
Message = "Hello world"});
(typed from memory)
call a function from constructor or anywhere as u like and add items like below
NewsFeedResources NFR=new NewsFeedResources(){Name=John, Id=5, Message="Stack overflow"};
_newsfeed.add(NFR);
NewsFeedResources NFR1 =new NewsFeedResources(){Name=Jane, Id=6, Message="Hello world"};
_newsfeed.add(NFR);