Create a dictionary in c# through lambda [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a following code:
var dict = new Dictionary<byte?, List<Id>>();
foreach (var record in Records)
{
if(record.SubId.HasValue)
{
dict.Add(SubIdsDictionary[record.SubId.Value], new List<Record> { record });
}
else
{
dict.Add(IdsDictionary[record.Id.Value], new List<Record> { record });
}
}
Records is the list of records for one name.In this record class I have Id,SubId and Companyname. Each name have id as mandatory but subid is not.So,if name has subid then I have to give priority to subid and first get the new sub id from the dictionary SubIdsDictionary(because subid is key in ref dict SubIdsDictionary) and make the new subid as key and the whole record as value in the new Dictionary dict. But if name dont have subid then i will use id and first get the new id from reference dict IdsDictionary and make the new id as key and value will be whole record.
Now in the new dictionary keys will be mix of ids and subids and record will be value as List
Can someone help me to convert this code through lambda?

You can use ToDictionary method from Linq.
It should looks like this:
var dict = Records.ToDictionary(
r => (r.SubId.HasValue ? SubIdsDictionary[r.SubId.Value] : IdsDictionary[r.Id.Value]),
r => new List<Record> {r}
);

Related

sort Dictionary by number of elemnts in List which is value for nested dictionary [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to sort dictionary by the number of elements in the List in the nested dictionary:
var evantData = new Dictionary>>()
This is my code..
var evantData = new Dictionary<string, Dictionary<string, List<string>>>
();
string input = "";
while ((input=Console.ReadLine())!="Time for Code")
{
string[] evantAndParticipants = input.Split().Select(x => x.Trim()).ToArray();
if (!evantData.ContainsKey(evantAndParticipants[0]))
{
evantData.Add(evantAndParticipants[0],new Dictionary<string, List<string>>());
evantData[evantAndParticipants[0]].Add(evantAndParticipants[1], new List<string>());
}
evantData[evantAndParticipants[0]][evantAndParticipants[1]].AddRange(evantAndParticipants.Skip(2));
}
foreach (var item in evantData)
{
foreach (var evant in item.Value)
{
Console.WriteLine(evant.Key+" - {0}",evant.Value.Count);
Console.WriteLine(string.Join("\r\n",evant.Value));
}
}
I want to sort the out by the number of elements in the List
Sorting a dictionary is inherently wrong, it doesn't make sense.
Now, if what you need are only the values sorted in some given order and you don't need the associated keys then you can simply do:
myDictionary.Values.OrderBy(v => v.Count);
If you need to sort the KeyValuePair<,> that make up your dictionary, then you can do:
var sortedKeyValuePairs = myDictionary.OrderBy(kv => kv.Value.Count);
But, this isn't normally what you'd want to do with a dictionary. You are either using the wrong tool or trying to do something the wrong way. Why do you need to do this?
Do note that none of the options above sorts your dictionary. You can't do that; they simply create new enumerations with the items stored in your dictionary sorted in the specified order.

How to remove null values elements from model list in C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I try to Extract data using LINQ query and adding into a model list.In this list only I need some of the fields values, but it's returning all the table fields include with null values. I have use model first approach so all the model classes will create the get set methods with all the table fields name so I want to remove some fields when I am retrieving the data Is it possible??
This my code
for (var z = 0; z < room_ament_list.Count(); z++)
{
var deal_room_amentity_id = room_ament_list[z];
var deal_room_amentity_details = db.deal_room_amentity.Where(a => a.room_amenity_id == deal_room_amentity_id).ToList();
foreach (var item_r_amentity in deal_room_amentity_details)
{
deal_room_amentity_list.Add(new deal_room_amentity()
{
room_amenity_id = item_r_amentity.room_amenity_id,
amenity_type = item_r_amentity.amenity_type,
});
}
}
this my table structure
And this is returning data from that list
But I need to Extract the data of what I have assigned in the list(without null elements).Is it possible to remove those null value element from the list??
If I am understanding your question correctly, you could modify you LINQ query as follows:
var deal_room_amentity_details = db.deal_room_amentity
.Where(a => a.room_amenity_id == deal_room_amentity_id
&& a.room_amenity_id != null).ToList();
You can download just the information you need from a SQL table by specifying an object definition in your Linq query.
var data = from x in db.deal_room_amentity
where
x.room_amenity_id == deal_room_amentity_id
select new {
id = x.id,
room_amenity_id = x.room_amenity_id
};
foreach(var item_r_amentity in data){
deal_room_amentity_list.Add(new deal_room_amentity()
{
room_amenity_id = item_r_amentity.room_amenity_id,
amenity_type = item_r_amentity.amenity_type,
});
}

how i can get the data that stored in list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to generate a random number from first list (list of Object) and put it in the second list to get a random connection id to make connection between the original id and the random id how I can get the item from the first list by index and of which type I have to cast it
public class OneHub :Hub
{
static List<UserId> ConnectedUser = new List<UserId>();
static List<MessageDetail> CurrentMessage = new List<MessageDetail>();
static List<ConnectionsId> Connection = new List<ConnectionsId>();
public void Connect(string id)
{
if (ConnectedUser.Count(x => x.ConnectionId == id) == 0)
{
ConnectedUser.Add(new UserId { ConnectionId = id });
if (ConnectedUser.Count != 0 || ConnectedUser.Count != 1)
{
Random r = new Random();
int x = r.Next(0,ConnectedUser.Count);
(object)ConnectedUser.item[x];
Connection.Add(new ConnectionsId {ConnectionId=id,ConnectionId2= })
}}}
First off, you're going to need to make sure that the ConnectedUser that you randomly get is not the same user you are linking to, before you add that connection, or you're going to find further issues.
For ConnectedUser, you can get the index by simply using ConnectedUser[x]. (I suggest making your lists plural so it's obvious that they're collections.)
You need to assign that connected user to a new object.
Something like
UserID linkedUser = ConnectedUser[x];
This way, you can reference linkedUser.ConnectionId in your connection addition.
Alternately, you could just use:
Connection.Add(new ConnectionsId { ConnectionId = id, ConnectionId2 = ConnectedUser[x].ConnectionId };
This random setup, though, does have a strong potential for having several people ending up not linked to anyone. Additionally, your line that states:
if (ConnectedUser.Count != 0 ...
is redundant. You just added a user to that list. It should never be of size 0.

C# initialize object [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The first 3 lines of code works fine..
How can I do the same when using object initializer ?
// works
Customer MyCustomerx = new Customer();
MyCustomerx.Location[0].place = "New York";
MyCustomerx.Location[1].place = "France";
// problem here
List<Customer> MyCustomer = new List<Customer>
{
new Customer() { Name= "Me",Location[0].place = "New York" }
}
There's no equivalent of that code within object initializers - you can't specify indexers like that. It's slightly unusual that it works even directly... I'd expect to have to add to a Locations property, rather than there being two already available which I could set an unconventionally-named property on. For example, this would be idiomatic:
Customer customer = new Customer {
Name = "Me",
Locations = {
new Location("New York"),
new Location("France")
}
};
(I'd probably put the name into a constructor parameter, mind you.)
You could then use that within a collection initializer, of course.

add value to a particular list in nested list C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to add a value to specific list from nested list. It will if there is any list contains a value called inputString, if yes, then add result into this list; if no, then create new list with result. The codes are as follows.
foreach(List<string> List in returnList )
{
if (List.Contains(inputString))
{
//add a string called 'result' to this List
}
else
{
returnList.Add(new List<string> {result});
}
}
The problem is in your else branch:
foreach (List<string> List in returnList)
{
if (List.Contains(inputString))
{
//add a string called 'result' to this List
List.Add(result); // no problem here
}
else
{
// but this blows up the foreach
returnList.Add(new List<string> { result });
}
}
The solution isn't hard,
// make a copy with ToList() for the foreach()
foreach (List<string> List in returnList.ToList())
{
// everything the same
}

Categories