Transform a Dictionary to List - c#

How can I transform this dictionary to list
var dict = new Dictionary<string, List<string>>();
dict.Add("1", new List<string>() { "a", "b" });
dict.Add("2", new List<string>() { "a", "c" });
I'm expecting this output
List<dynamic> = new List<dynamic>()
{
new { id = "1", value = "a" }
new { id = "1", value = "a" }
new { id = "2", value = "a" }
new { id = "2", value = "a" }
}
I've tried this but can't get the values of the nested collections:
dict.Select(c => new { id=c.Key, value= c.Value })

Use SelectMany to return multiple items for each KeyValuePair. Then for each pair use Select on the Value:
var result = dict.SelectMany(pair => pair.Value.Select(item =>
new { id = pair.Key, value = item }));
Result:

Related

EFCore migrationBuilder insertData: I can't seem to convert data from table into object[,]

I'm trying to insert data in a migration using migrationBuilder.InsertData. According to the docs, I should be able to insert multiple rows with multiple columns using InSertData(String, String[], String[], Object[,], String) but I can't seem to format my data properly for the Object[,] values.
The code below is just sample code that I'm using on dotnetfiddle so that I could easier see what my data was looking like.
class MyModel
{
public string name {get; set;}
public bool active {get; set;}
}
public class Program
{
public static void Main()
{
var e = new String[] {"b", "c", "d"};
var x = new List<MyModel>() {
new MyModel {name = "f", active = false},
new MyModel {name = "a", active = false},
new MyModel {name = "b", active = false},
new MyModel {name = "c", active = false},
new MyModel {name = "d", active = false},
new MyModel {name = "e", active = false},
new MyModel {name = "f", active = false},
new MyModel {name = "f", active = false},
new MyModel {name = "f", active = false},
};
var _data = x.Select(a => a.name)
.Distinct()
.OrderBy(a => a)
.Select(a => new object[] {a, e.Contains(a) ? 0 : 1})
.ToArray();
Console.WriteLine(JsonConvert.SerializeObject(_data)); // for testing purposes
Console.WriteLine(_data[1][0]); // b
Console.WriteLine(_data is Array); // true
Console.WriteLine(((Array)_data).Rank == 2); // false
Console.WriteLine(((Array)_data).Rank); // 1
}
}
In my migration file:
migrationBuilder.InsertData(
table:'Model',
columns: new string[] {"name","active"},
columnTypes: new string[] {"string","bit"},
values: _data // This throws an error: The number of values (38) doesn't match the number of columns(2) for the data insertion operation.
)

filter on CollectionProperties gives me all 4 records instead of 2

I have a list lstCollectionInstances which has 4 collection instance,
var lstCollectionInstances = new List<CollectionInstance>
{
new CollectionInstance
{
Name = "A",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P1", Value = 10, DataType = "D"}
}
},
new CollectionInstance
{
Name = "A",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P2", Value = "H1", DataType = "S"}
}
},
new CollectionInstance
{
Name = "B",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P1", Value = 20, DataType = "D"}
}
},
new CollectionInstance
{
Name = "B",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P2", Value = "H2", DataType = "S"}
}
},
};
Now when I filter it based on CollectionProperty data types D it's should give me 2 records, but below code giving me all 4 records, what is missing here?
var X = lstCollectionInstances.Select(x => new CollectionInstance
{
Name = x.Name,
CollectionProperties = x.CollectionProperties.Where(cp => cp.DataType == "D").ToList()
}).ToList();
This one selects all instances with a property of type D.
var result= lstCollectionInstances
.Where(x => x.CollectionProperties.Any(y => y.DataType == "D"))
.ToList();
It is because you're executing Select in each item of lstCollectionInstances and Where in CollectionProperties. It will return 4 items which 2 of them have empty CollectionProperties. You should execute Where first like:
var X = lstCollectionInstances.Where(a => a.CollectionProperties.Any(cp => cp.DataType == "D")).Select(x => new CollectionInstance
{
Name = x.Name,
CollectionProperties = x.CollectionProperties
}).ToList();

Dynamic linq query with nested groups

I'm trying to create nested group with dynamic query.
Following are my collection of data
var invoices = new List < Purchase > () {
new Purchase() {
Id = 1, Customer = "a", Date = DateTime.Parse("1/1/2009")
}, new Purchase() {
Id = 2, Customer = "a", Date = DateTime.Parse("1/2/2009")
}, new Purchase() {
Id = 3, Customer = "a", Date = DateTime.Parse("1/2/2009")
}, new Purchase() {
Id = 4, Customer = "b", Date = DateTime.Parse("1/1/2009")
}, new Purchase() {
Id = 5, Customer = "b", Date = DateTime.Parse("1/1/2009")
}, new Purchase() {
Id = 6, Customer = "b", Date = DateTime.Parse("1/2/2009")
}
};
This linq query is returning the desired result.
var tree = invoices.GroupBy(x => x.Date).Select(x => new
{
Key = x.Key,
Items = x.GroupBy(y => y.Customer).Select(y => new
{
Key = y.Key,
Items = y
})
}).ToList();
Below is the output of the above linq query
But I just need to group different columns in different order.
So that I try to create dynamic linq query. But my code block result not same as my previous linq query.
var groupedInvoiceItems = invoices.AsQueryable().GroupBy("new (Date, Customer)", "it");
You could do this with Generics. Just Pass in your Lambda to a generic method.
Something like:
private IEnumerable<PurchaseGrp> BuildList<TSource>(IQueryable<TSource> allRecords,
Func<TSource, string> selector)
{
var result = allRecords.GroupBy(x = > x.selector(x));
return result;
}
The return type could be a new Grouped type PurchaseGrp or the same as your source (Purchase).

Multiselect chosen dropdown - want to set values

Please let me know how can I set the selected value in the chosen multiselect dropdownlist. I have tried everything available on net but nothing is working.
My view is
#Html.DropDownListFor(
model => model.SelectedSkills,
new SelectList(
Model.SkillList,
"Value",
"Text",
Model.SelectedSkills
),
new {
#class = "chosen",
id = "ddlSkill",
name="ddlPersonSkill",
#tabindex = "4",
multiple = "true"
}
)
#Html.HiddenFor(
model => model.SelectedSkills,
new { id = "hdnPersonSkill" }
)
Now in page load I need to display the selected value :
var personskill = $("#hdnPersonSkill").val();
$('#ddlSkill option:nth-child(3)').attr('selected', 'selected');
$('#ddlSkill').trigger('liszt:updated');
But above code is not working
CHHTML:
#Html.ListBoxFor(
model => model.SelectedSkills,
new SelectList(
Model.SkillList,
"Value",
"Text",
Model.SelectedSkills
),
new
{
#class = "chosen",
id = "ddlSkill",
name = "ddlPersonSkill",
#tabindex = "4",
multiple = "true"
}
)
Javascript to show all selected:
$(document).ready(function () {
var conceptName = $('#ddlSkill').find(":selected").text();
alert(conceptName);
});
Model jsut for example:
public string[] SelectedSkills { get; set; }
public IEnumerable<SelectListItem> SkillList { get; set; }
public MyModel()
{
SkillList = new List<SelectListItem>();
((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 1", Value = "1" });
((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 2", Value = "2" });
((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 3", Value = "3" });
((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 4", Value = "4" });
SelectedSkills = new string[3];
SelectedSkills[0] = "1";
SelectedSkills[1] = "2";
SelectedSkills[2] = "3";
}

LINQ return non-matching items query

I have 2 arrays of different types one is from file and one is from a SQL Database - LINQ to SQL. I'm trying to delete non matching items from my database against items I receive via the file. (I mention this in case there is a more efficient way to do what I'm trying to achieve).
I've drafted up a couple of anonymous arrays to show what I am trying to do:
var a = new[] {
new { code = "A", subid = 1, test = "dunno" }, new { code = "A", subid = 2, test = "dunno" }, new { code = "A", subid = 3, test = "dunno" },
new { code = "B", subid = 1, test = "dunno" }, new { code = "B", subid = 2, test = "dunno" }, new { code = "B", subid = 3, test = "dunno" }
};
var c = new[] {
new { code = "A", subid = 1 }, new { code = "A", subid = 2 },
new { code = "B", subid = 1 }, new { code = "B", subid = 2 }
};
I need it to return the items that do not match e.g. new { code = "A", subid = 3 } and new { code = "B", subid = 3 }
var b = (from items in a
where c.Any(d => d.code == items.code && d.subid != items.subid)
select items);
and
var b = (from items in a
where c.Where(d=> d.code == items.code).Any(d => d.subid != items.subid)
select items);
I've tried these but they just seem to return all the items. How do I do this?
Use Enumerable.Except
var nonMatchingItems = a.Except(c);
Full sample:
var a = new[] {
new { code = "A", subid = 1 },
new { code = "A", subid = 2 },
new { code = "A", subid = 3 },
new { code = "B", subid = 1 },
new { code = "B", subid = 2 },
new { code = "B", subid = 3 }
};
var c = new[] {
new { code = "A", subid = 1 },
new { code = "A", subid = 2 },
new { code = "B", subid = 1 },
new { code = "B", subid = 2 }
};
foreach(vat item in a.Except(c))
Console.WriteLine(item);
// { code = A, subid = 3 }
// { code = B, subid = 3 }
UPDATE (if you have different types, and want to find matches of some set of fields, then use join of sequences, and remove all items from a which matched some items in c:
var matchingItems = from aa in a
join cc in c
on new { aa.code, aa.subid } equals // properties subset
new { cc.code, cc.subid } // same subset
select aa; // select inner item from join
var nonMatchingItems = a.Except(matchingItems);

Categories

Resources